agentkit

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 30 Imported by: 0

README

AgentKit

CI

中文文档

A lightweight, event-stream-driven Agent toolkit built on top of CloudWeGo Eino ADK.

Inspired by pi-agent-core, AgentKit brings event streaming, message queuing, and human-in-the-loop (HITL) capabilities to the Go + Eino ecosystem.

Features

  • Event-stream architecture — Subscribe to fine-grained events (message deltas, tool calls, errors, etc.)
  • Steering & follow-up queues — Inject messages mid-execution to redirect the agent or append follow-up tasks
  • Human-in-the-loop (HITL) — Interrupt agent execution and resume with user-provided data
  • Streaming support — Real-time token-by-token output via Eino ADK streaming
  • Reasoning model support — First-class support for thinking/reasoning models (DeepSeek-R1, o1, etc.) with streaming reasoning output
  • Multimodal input — Send text, images, audio, video, and files via Send() with ergonomic constructors
  • Session persistence — Automatically save and restore complete conversations with built-in concurrent memory and atomic file stores
  • Automatic context compaction — Summarize contexts over token or message limits while preserving full conversation history
  • On-demand skills — Load reusable SKILL.md instructions from local directories or a custom backend
  • Managed MCP connections — Connect stdio, SSE, and Streamable HTTP servers with discovery, reconnection, filtering, and cleanup
  • Tool integration — Plug in any Eino-compatible tool with automatic tool-call handling
  • Type aliases — Use agentkit.ChatModel, agentkit.Tool, agentkit.ToolCall, etc. without importing eino packages directly

Installation

AgentKit requires Go 1.25.14 or later.

go get github.com/wsshow/agentkit@latest

Quick 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",
		BaseURL: "https://api.openai.com/v1",
		Model:   "gpt-4o",
	})
	if err != nil {
		log.Fatalln(err)
	}

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

	agent.Subscribe(func(e agentkit.Event) {
		switch e.Type {
		case agentkit.EventReasoningDelta:
			fmt.Print(e.Delta) // reasoning/thinking stream (for reasoning models)
		case agentkit.EventMessageDelta:
			fmt.Print(e.Delta)
		case agentkit.EventMessageEnd:
			fmt.Println()
		case agentkit.EventError:
			fmt.Printf("Error: %v\n", e.Error)
		}
	})

	if err := agent.Prompt(ctx, "Hello!"); err != nil {
		log.Fatalln(err)
	}
}

Event Types

Event Description
EventAgentStart Agent begins processing
EventTurnStart New turn starts before the next model request
EventMessageStart Message begins (Event.Role identifies user, assistant, or tool)
EventReasoningDelta Reasoning/thinking stream delta (Event.Delta), for reasoning models
EventMessageDelta Incremental streaming text (Event.Delta)
EventMessageEnd Message complete (Event.Role, Event.Content, Event.ResponseMeta)
EventToolStart Tool call requested (Event.ToolCalls)
EventToolUpdate Tool execution progress update (Event.ToolCallID, Event.Content)
EventToolEnd Tool call result returned (Event.ToolCallID, Event.ToolName, Event.Content)
EventTurnEnd Turn complete after the assistant message and tool results
EventTransfer Agent transfer (multi-agent)
EventInterrupted HITL interrupt (Event.Interrupt)
EventCompactionStart Automatic context compaction started (Event.Compaction.MessagesBefore)
EventCompactionEnd Automatic context compaction completed (Event.Compaction)
EventAgentEnd Agent processing complete
EventError Error occurred (Event.Error)
Event Struct
type Event struct {
    Type             EventType
    Agent            string           // source agent name
    Role             RoleType         // message role (message_start / message_end)
    Content          string           // full text (message_end / tool_end)
    Delta            string           // streaming delta (message_delta / reasoning_delta)
    ReasoningContent string           // full reasoning content (message_end, reasoning models only)
    ResponseMeta     *ResponseMeta    // token usage, finish reason (message_end)
    ToolCalls        []ToolCall       // tool call list (tool_start)
    ToolCallID       string           // tool call ID (tool_update / tool_end)
    ToolName         string           // tool name (tool_update / tool_end)
    ToolArguments    string           // tool arguments (tool_update / tool_end)
    Interrupt        []InterruptPoint // interrupt points (interrupted)
    Compaction       *CompactionInfo  // context message counts before/after compaction
    Error            error            // error details (error)
}

API Reference

Creating an Agent
agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:            "my-agent",
    Description:     "Agent description",
    SystemPrompt:    "System instructions",
    Model:           chatModel,                          // agentkit.ChatModel
    Tools:           []agentkit.Tool{myTool},             // optional
    Handlers:         []agentkit.ChatModelAgentMiddleware{myHandler}, // optional
    ModelRetryConfig: &agentkit.ModelRetryConfig{MaxRetries: 2},      // optional
    ModelFailoverConfig: failoverConfig,                              // optional
    MaxIterations:   20,                                  // max LLM call cycles (default: 20)
    CheckPointStore: store,                               // checkpoint store (optional)
    Session: &agentkit.SessionConfig{                     // automatic restore/save (optional)
        ID: "user-123",
        Store: sessionStore,
    },
    Compaction: &agentkit.CompactionConfig{               // automatic context compaction (optional)
        MaxTokens: 80_000,
        KeepRecentTurns: 2,
    },
    Skills: &agentkit.SkillsConfig{                       // on-demand SKILL.md loading (optional)
        Paths: []string{"./skills"},
    },
    MCP: &agentkit.MCPConfig{                             // managed MCP servers (optional)
        Servers: []agentkit.MCPServerConfig{{
            Name:      "search",
            Transport: agentkit.MCPTransportStreamableHTTP,
            URL:       "https://mcp.example.com/mcp",
        }},
    },
})
defer agent.Close()

For manual history restoration, use History: savedHistory instead of Session; the two options are mutually exclusive.

Core Methods
// Send user text input and drive agent execution (blocking, thread-safe)
err := agent.Prompt(ctx, "user message")

// Send multimodal input (text + images, audio, video, files)
err := agent.Send(ctx,
    agentkit.Text("What is in this image?"),
    agentkit.ImageURL("https://example.com/cat.jpg"),
)

// Resume from current state without new message (e.g. retry after error)
err := agent.Continue(ctx)

// Resume from a HITL interrupt
err := agent.Resume(ctx, map[string]any{"interruptID": data})

// Subscribe to events, returns unsubscribe function
unsubscribe := agent.Subscribe(func(e agentkit.Event) { ... })

// Request cancellation without blocking (safe inside subscribers)
agent.Cancel()

// Cancel current execution and wait for completion (call outside subscribers)
agent.Abort()

// Reset agent state (waits for completion, then clears history and queues)
agent.Reset()

// Get full conversation history for debugging or persistence (returns a copy)
history := agent.History()

// Get the context actually sent to the model (same as History before compaction)
contextHistory := agent.ContextHistory()

// Replace full conversation history and sync display state
agent.SetHistory(history)

// Get a session snapshot; Prompt/Send/Continue/Resume save automatically
session := agent.Session()

// Save immediately after a manual change such as SetHistory
err := agent.SaveSession(ctx)

// Get agent state (message records, streaming status)
state := agent.State()

// Close agent and release resources (implements io.Closer)
agent.Close()

Prompt, Send, Continue, and Resume are mutually exclusive. Use errors.Is(err, agentkit.ErrAgentRunning) to detect a concurrent run.

Session Management

Configure a session ID and store. New restores an existing conversation, and every run is saved automatically—even when the model fails or the run is canceled:

store, err := agentkit.NewFileSessionStore("./data/sessions")
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,
    },
})

The file store uses safe hashed file names and atomic replacement, preventing path traversal through session IDs and half-written JSON after a crash. Manage sessions directly through the store:

sessions, err := store.List(ctx)
saved, err := store.Load(ctx, "user-123")
err = store.Delete(ctx, "user-123") // deleting a missing session also succeeds

Use agentkit.NewMemorySessionStore() for tests and single-process services. Implement agentkit.SessionStore for a database backend. History and Session cannot be configured together, so the restore source is always unambiguous. Only one Agent should write a given session ID at a time: the built-in stores are concurrency-safe, but they do not merge divergent conversations.

Automatic Context Compaction

Enable Compaction to summarize context after a configured limit while preserving the most recent user turns verbatim:

agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:  "assistant",
    Model: chatModel,
    Compaction: &agentkit.CompactionConfig{
        MaxTokens:       80_000, // keep below the model's context window
        MaxMessages:     100,    // optional; either limit can trigger
        KeepRecentTurns: 2,      // default: 1
        Model:           summaryModel, // optional; defaults to the main model
    },
})

The two history views have distinct responsibilities:

  • History() always returns the full, unabridged conversation for UI, auditing, and export.
  • ContextHistory() returns the compacted context actually sent to the model.
  • With Session configured, both are persisted so a restart does not accidentally restore the full history into the model context.

With no explicit limit, compaction starts above the estimated DefaultCompactionMaxTokens (100,000). Summary errors are returned normally and never replace the original context. Subscribe to EventCompactionStart and EventCompactionEnd to show progress.

Skills

Put each reusable skill in its own directory:

skills/
└── concise-answer/
    └── SKILL.md
---
name: concise-answer
description: Keep answers short and direct
---
Answer in no more than three short sentences.

Then enable the directory on the agent:

agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:  "assistant",
    Model: chatModel,
    Skills: &agentkit.SkillsConfig{
        Paths: []string{"./skills"},
        // ToolName: "load_skill", // optional; defaults to "skill"
    },
})

Paths accepts a SKILL.md file, one skill directory, or a collection directory whose immediate child directories contain skills. Files are reloaded on every list or load operation, so edits take effect without rebuilding the agent. Duplicate names, malformed frontmatter, missing instructions, and files over 1 MiB fail with an explicit error.

For programmatic or remote storage, pass Backend instead of Paths. AgentKit includes a concurrency-safe NewMemorySkillBackend and exposes the small SkillBackend interface for custom implementations. The simple configuration intentionally supports inline skills only; skills requesting context, agent, or model overrides fail fast. Applications that need Eino's advanced fork/model routing can install a fully configured Eino skill middleware through Handlers.

MCP Management

AgentKit can connect MCP servers, discover their tools, expose them to the model, reconnect after connection-level failures, and close every session with the agent:

agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:  "assistant",
    Model: chatModel,
    MCP: &agentkit.MCPConfig{
        Servers: []agentkit.MCPServerConfig{
            {
                Name:       "search",
                Transport:  agentkit.MCPTransportStreamableHTTP,
                URL:        "https://mcp.example.com/mcp",
                Headers:    map[string]string{"Authorization": "Bearer " + token},
                ToolNames:  []string{"search", "fetch"}, // optional allowlist
                ToolPrefix: "search__",                  // optional namespace
            },
        },
    },
})
if err != nil {
    log.Fatal(err)
}
defer agent.Close() // also closes all MCP sessions

For a local stdio server:

MCP: &agentkit.MCPConfig{
    Servers: []agentkit.MCPServerConfig{{
        Name:       "filesystem",
        Transport:  agentkit.MCPTransportStdio,
        Command:    "filesystem-mcp",
        Args:       []string{"--root", workspace},
        Env:        map[string]string{"LOG_LEVEL": "warn"}, // merged with the process environment
        WorkingDir: workspace,
        ToolPrefix: "fs__",
    }},
},

MCPTransportSSE is available for legacy SSE servers. Tool lists are fully paginated once during New; recreate the agent to pick up later additions or removals. Exposed tool names must be unique, so configure ToolPrefix when servers—or local tools—use the same name. A requested ToolNames entry that the server does not provide is an initialization error instead of a silent omission.

To keep a single response from exhausting model context, MCP results default to DefaultMCPMaxResultChars (100,000 characters) and tool descriptions to DefaultMCPMaxDescriptionChars (4,000). Set either MCPConfig limit to a positive value to customize it or -1 to disable it. Static headers are copied during initialization; use a custom HTTPClient with an authentication RoundTripper when credentials must refresh dynamically, and avoid hard-coding secrets.

Advanced callers can provide an already-connected MCPClientSession instead of transport settings. AgentKit takes ownership of that session and closes it on initialization failure or Agent.Close.

Integration Tests

Use MockChatModel to run agents without calling a real model:

model := agentkit.NewMockChatModel(
    agentkit.MockModelStream("hel", "lo"),
)

agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:  "test-agent",
    Model: model,
})
if err != nil {
    t.Fatal(err)
}
defer agent.Close()

if err := agent.Prompt(ctx, "say hello"); err != nil {
    t.Fatal(err)
}

calls := model.Calls()
if calls[0].Input[len(calls[0].Input)-1].Content != "say hello" {
    t.Fatal("unexpected input")
}

Common response helpers:

agentkit.MockModelText("done")
agentkit.MockModelStream("part 1", "part 2")
agentkit.MockModelError(err)
agentkit.MockModelStreamError(err, "partial")

Tool calls can execute real functions:

weather := agentkit.MustMockTool(
    "get_weather",
    "query weather",
    func(ctx context.Context, input *WeatherInput) (*WeatherOutput, error) {
        return &WeatherOutput{City: input.City, Condition: "sunny"}, nil
    },
)

beijing := weather.Call("beijing_weather", &WeatherInput{City: "Beijing"})
shanghai := weather.Call("shanghai_weather", &WeatherInput{City: "Shanghai"})

model := agentkit.NewMockChatModel(
    agentkit.MockModelCalls(beijing),
    agentkit.MockModelCallsAfter(beijing, shanghai),
    agentkit.MockModelRespondsAfter(shanghai, func(out *WeatherOutput) agentkit.MockModelResponse {
        return agentkit.MockModelText(out.City + " is " + out.Condition)
    }),
)

agent, err := agentkit.New(ctx, &agentkit.Config{
    Name:  "test-agent",
    Model: model,
    Tools: agentkit.MockTools(weather),
})

Use MockModelCalls when one model response calls multiple tools:

beijing := weather.Call("beijing_weather", &WeatherInput{City: "Beijing"})
shanghai := weather.Call("shanghai_weather", &WeatherInput{City: "Shanghai"})

model := agentkit.NewMockChatModel(
    agentkit.MockModelCalls(beijing, shanghai),
    agentkit.MockModelTextAfterAll("done", beijing, shanghai),
)
Steering & Follow-Up
// Inject a steering message during execution (checked after the current tool batch)
agent.Steer("Please focus on topic X instead")

// Append a follow-up message (processed after current task completes)
agent.FollowUp("Also check Y")

// Configure queue processing mode
agent.SetSteeringMode(agentkit.QueueModeAll)        // process all queued messages at once
agent.SetFollowUpMode(agentkit.QueueModeOneAtATime)  // process one at a time (default)

// Clear queues
agent.ClearSteeringQueue()
agent.ClearFollowUpQueue()
agent.ClearAllQueues()
HITL (Human-in-the-Loop)
// In a tool: trigger interrupt
return "", agentkit.Interrupt(ctx, "Need user confirmation")

// With state preservation
return "", agentkit.StatefulInterrupt(ctx, "Confirm?", myState)

// In a resumed tool: check interrupt state
wasInterrupted, hasState, state := agentkit.GetInterruptState[MyState](ctx)

// Get resume data from user
isTarget, hasData, data := agentkit.GetResumeContext[bool](ctx)
Multimodal Input

Send accepts variadic ContentPart values built with constructor functions:

// Text + image
agent.Send(ctx,
    agentkit.Text("What is in this image?"),
    agentkit.ImageURL("https://example.com/cat.jpg"),
)

// Image with quality control
agent.Send(ctx,
    agentkit.Text("Describe in detail"),
    agentkit.ImageURL("https://example.com/photo.jpg", agentkit.ImageDetailHigh),
)

// Base64 encoded image
agent.Send(ctx,
    agentkit.Text("Identify this"),
    agentkit.ImageBase64(base64Data, "image/png"),
)

// Audio / Video / File
agent.Send(ctx, agentkit.Text("Transcribe"), agentkit.AudioURL("https://example.com/speech.mp3"))
agent.Send(ctx, agentkit.Text("Summarize"), agentkit.VideoURL("https://example.com/clip.mp4"))
agent.Send(ctx, agentkit.Text("Analyze"), agentkit.FileURL("https://example.com/report.pdf"))

Available constructors:

Constructor Description
Text(s) Text content
ImageURL(url, detail...) Image from URL (optional quality)
ImageBase64(data, mime, detail...) Image from Base64
AudioURL(url) Audio from URL
AudioBase64(data, mime) Audio from Base64
VideoURL(url) Video from URL
VideoBase64(data, mime) Video from Base64
FileURL(url) File from URL
FileBase64(data, mime, name...) File from Base64 (optional filename)
Tool Progress Updates

Tools can emit progress events during execution:

func myTool(ctx context.Context, input string) (string, error) {
    agentkit.EmitToolUpdate(ctx, "Processing step 1...")
    // ... do work ...
    agentkit.EmitToolUpdate(ctx, "Processing step 2...")
    return "result", nil
}
Type Aliases

AgentKit provides type aliases so consumers don't need to import eino packages directly:

Alias Eino Type
ChatModel model.BaseChatModel
Tool tool.BaseTool
ToolCall schema.ToolCall
ResponseMeta schema.ResponseMeta
TokenUsage schema.TokenUsage
ContentPart schema.MessageInputPart
ImageURLDetail schema.ImageURLDetail

Examples

See the examples directory:

  • simple — Minimal multi-turn conversation (~60 lines)
  • tools — Tool calls with progress events
  • history — Export and restore conversation history
  • session — Automatically persist and restore sessions across processes
  • compaction — Automatically compact long conversation contexts
  • skills — Load reusable instructions from local SKILL.md files
  • mcp — Connect and call a Streamable HTTP MCP server
  • queues — Follow-up and steering queues
  • hitl — Human-in-the-loop interrupt and resume
  • multimodal — Text and image inputs

License

See LICENSE for details.

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

View Source
const (
	// DefaultMCPMaxResultChars 是单次 MCP 工具结果默认保留的最大字符数。
	DefaultMCPMaxResultChars = 100_000
	// DefaultMCPMaxDescriptionChars 是单个 MCP 工具描述默认保留的最大字符数。
	DefaultMCPMaxDescriptionChars = 4_000
)
View Source
const DefaultCompactionMaxTokens = 100_000

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

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")
)
View Source
var (
	// ErrSessionNotFound 表示会话存储中不存在指定会话。
	ErrSessionNotFound = errors.New("agentkit: session not found")
	// ErrSessionDisabled 表示 Agent 未配置会话存储。
	ErrSessionDisabled = errors.New("agentkit: session persistence is not configured")
)
View Source
var ErrMockModelNoResponse = errors.New("mock chat model has no response configured")

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

View Source
var ErrSkillNotFound = errors.New("agentkit: skill not found")

ErrSkillNotFound 表示指定技能不存在。

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 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 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
}

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 回调与执行处于同一 goroutine,回调内请使用 Cancel 以避免等待自身。

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) 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) 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) 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) 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) 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) Subscribe

func (a *Agent) Subscribe(fn Subscriber) func()

Subscribe 订阅事件流,返回取消订阅函数。 回调按订阅顺序同步执行,每个回调收到独立的事件快照;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 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 别名)
	History             []*schema.Message          // 完整对话历史(可选)
	Handlers            []ChatModelAgentMiddleware // ChatModelAgent 扩展处理器
	ModelRetryConfig    *ModelRetryConfig          // 模型调用重试配置(可选)
	ModelFailoverConfig *ModelFailoverConfig       // 模型失败转移配置(可选)
	MaxIterations       int                        // 默认 20
	CheckPointStore     compose.CheckPointStore    // 自定义 CheckPoint 存储,默认使用内存存储
	Session             *SessionConfig             // 自动恢复并保存完整对话(可选)
	Compaction          *CompactionConfig          // 自动上下文压缩(可选)
	Skills              *SkillsConfig              // 按需加载 SKILL.md(可选)
	MCP                 *MCPConfig                 // 自动连接并管理 MCP 服务器(可选)
}

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 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)
	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"   // 上下文压缩完成
	EventAgentEnd        EventType = "agent_end"        // Agent 处理完成
	EventError           EventType = "error"            // 错误
)

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

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

Delete 删除会话文件。会话不存在时也返回 nil。

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

func (s *FileSessionStore) Save(ctx context.Context, session *Session) error

Save 通过原子文件替换保存会话快照。

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 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 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 服务器

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

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

Delete 删除会话。会话不存在时也返回 nil。

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

func (s *MemorySessionStore) Save(ctx context.Context, session *Session) error

Save 保存并完全替换会话快照。

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 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 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 RoleType

type RoleType string

RoleType 消息角色类型

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

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 相同
}

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"`
}

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 调用,并且不得保留调用方传入的可变切片。

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 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 ToolCall

type ToolCall = schema.ToolCall

ToolCall 工具调用信息

Jump to

Keyboard shortcuts

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