devui

package
v0.5.11 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package devui 提供 Hexagon 开发调试界面

DevUI 是一个轻量级的 Web 调试界面,用于实时查看 Agent 执行过程、 LLM 调用、工具执行、RAG 检索等信息。

特性:

  • 实时事件流推送(SSE)
  • Span 追踪可视化
  • 指标仪表板
  • 零侵入集成(利用现有 Hooks + Tracer)

快速使用:

ui := devui.New(devui.WithAddr("127.0.0.1:8080"))
defer func() {
    if err := ui.Stop(context.Background()); err != nil {
        log.Printf("Dev UI shutdown failed: %v", err)
    }
}()

ctx := hooks.ContextWithManager(context.Background(), ui.HookManager())
go func() {
    if err := ui.Start(); err != nil {
        log.Printf("Dev UI stopped: %v", err)
    }
}()
// 使用 ctx 执行 Agent,并访问 http://localhost:8080。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORSMiddleware

func CORSMiddleware(allowOrigin string) func(http.Handler) http.Handler

CORSMiddleware CORS 中间件

func ChainMiddleware

func ChainMiddleware(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler

ChainMiddleware 链接多个中间件

func LoggingMiddleware

func LoggingMiddleware(next http.Handler) http.Handler

LoggingMiddleware 日志中间件

func RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware 恢复中间件 捕获 panic 并返回 500 错误

func ReleaseEvent

func ReleaseEvent(e *Event)

ReleaseEvent 将事件对象归还到对象池

Types

type AgentEndData

type AgentEndData struct {
	RunID    string         `json:"run_id"`
	Output   any            `json:"output"`
	Duration int64          `json:"duration_ms"` // 毫秒
	Metadata map[string]any `json:"metadata,omitempty"`
}

AgentEndData Agent 结束事件数据

type AgentStartData

type AgentStartData struct {
	RunID    string         `json:"run_id"`
	Input    any            `json:"input"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

AgentStartData Agent 开始事件数据

type Breakpoint

type Breakpoint struct {
	// NodeID 断点所在节点
	NodeID string `json:"node_id"`

	// Condition 条件表达式(可选,空表示无条件断点)
	Condition string `json:"condition,omitempty"`

	// Enabled 是否启用
	Enabled bool `json:"enabled"`
}

Breakpoint 断点定义

type BuilderExecutor

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

BuilderExecutor 可视化构建器的图执行引擎

将 GraphDefinition 转换为 graph.Graph[graph.MapState] 并执行。 MVP 阶段节点使用 echo handler(记录执行信息到状态), 后续可扩展为真正调用 Agent/Tool/LLM。

func NewBuilderExecutor

func NewBuilderExecutor(collector *Collector) *BuilderExecutor

NewBuilderExecutor 创建执行器

func (*BuilderExecutor) Execute

func (e *BuilderExecutor) Execute(ctx context.Context, def *GraphDefinition, initialState map[string]any) (*ExecutionResult, error)

Execute 执行图定义

将 GraphDefinition 构建为 graph.Graph[graph.MapState] 并使用同步 Run() 执行。 节点 handler 内部记录执行结果并发送 SSE 事件,避免 Stream() 的并发竞态。

type Collector

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

Collector 事件收集器

收集器实现了 hooks.RunHook、hooks.ToolHook、hooks.LLMHook、hooks.RetrieverHook 接口, 用于收集 Agent 执行过程中的各种事件,并广播给 SSE 订阅者。

特性:

  • 实现所有 Hook 接口,自动收集事件
  • 环形缓冲区存储历史事件
  • 支持多个 SSE 订阅者
  • 内置 MemoryTracer 用于 Span 追踪

func NewCollector

func NewCollector(maxEvents int) *Collector

NewCollector 创建事件收集器

参数:

  • maxEvents: 最大事件缓存数量

func (*Collector) EmitError

func (c *Collector) EmitError(runID, source, message, stack string)

EmitError 发送错误事件

func (*Collector) EmitGraphEnd

func (c *Collector) EmitGraphEnd(runID, graphID string, state map[string]any, durationMs int64)

EmitGraphEnd 发送图执行结束事件

func (*Collector) EmitGraphNode

func (c *Collector) EmitGraphNode(runID, graphID, nodeID, nodeName string, state map[string]any, durationMs int64)

EmitGraphNode 发送图节点执行事件

func (*Collector) EmitGraphStart

func (c *Collector) EmitGraphStart(runID, graphID, graphName string, state map[string]any)

EmitGraphStart 发送图执行开始事件

func (*Collector) EmitStateChange

func (c *Collector) EmitStateChange(agentID, key string, oldValue, newValue any)

EmitStateChange 发送状态变更事件

func (*Collector) Enabled

func (c *Collector) Enabled() bool

Enabled 返回钩子是否启用

func (*Collector) Events

func (c *Collector) Events() *RingBuffer

Events 返回事件缓冲区

func (*Collector) Name

func (c *Collector) Name() string

Name 返回钩子名称

func (*Collector) OnEnd

func (c *Collector) OnEnd(ctx context.Context, evt *hooks.RunEndEvent) error

OnEnd Agent 执行结束

func (*Collector) OnError

func (c *Collector) OnError(ctx context.Context, evt *hooks.ErrorEvent) error

OnError Agent 执行错误

func (*Collector) OnLLMEnd

func (c *Collector) OnLLMEnd(ctx context.Context, evt *hooks.LLMEndEvent) error

OnLLMEnd LLM 调用结束

func (*Collector) OnLLMStart

func (c *Collector) OnLLMStart(ctx context.Context, evt *hooks.LLMStartEvent) error

OnLLMStart LLM 调用开始

func (*Collector) OnLLMStream

func (c *Collector) OnLLMStream(ctx context.Context, evt *hooks.LLMStreamEvent) error

OnLLMStream LLM 流式输出

func (*Collector) OnRetrieverEnd

func (c *Collector) OnRetrieverEnd(ctx context.Context, evt *hooks.RetrieverEndEvent) error

OnRetrieverEnd 检索结束

func (*Collector) OnRetrieverStart

func (c *Collector) OnRetrieverStart(ctx context.Context, evt *hooks.RetrieverStartEvent) error

OnRetrieverStart 检索开始

func (*Collector) OnStart

func (c *Collector) OnStart(ctx context.Context, evt *hooks.RunStartEvent) error

OnStart Agent 开始执行

func (*Collector) OnToolEnd

func (c *Collector) OnToolEnd(ctx context.Context, evt *hooks.ToolEndEvent) error

OnToolEnd 工具执行结束

func (*Collector) OnToolStart

func (c *Collector) OnToolStart(ctx context.Context, evt *hooks.ToolStartEvent) error

OnToolStart 工具开始执行

func (*Collector) SetEnabled

func (c *Collector) SetEnabled(enabled bool)

SetEnabled 设置钩子是否启用

func (*Collector) Stats

func (c *Collector) Stats() CollectorStats

Stats 返回统计信息

func (*Collector) Subscribe

func (c *Collector) Subscribe() (<-chan *Event, func())

Subscribe 订阅事件流 返回事件通道和取消订阅函数

注意:取消订阅函数只能调用一次,重复调用会导致 panic

func (*Collector) SubscriberCount

func (c *Collector) SubscriberCount() int

SubscriberCount 返回当前订阅者数量

func (*Collector) Tracer

func (c *Collector) Tracer() *tracer.MemoryTracer

Tracer 返回内置的 MemoryTracer

type CollectorStats

type CollectorStats struct {
	TotalEvents   int64 `json:"total_events"`
	AgentRuns     int64 `json:"agent_runs"`
	LLMCalls      int64 `json:"llm_calls"`
	ToolCalls     int64 `json:"tool_calls"`
	RetrieverRuns int64 `json:"retriever_runs"`
	Errors        int64 `json:"errors"`
	Subscribers   int   `json:"subscribers"`
	BufferSize    int   `json:"buffer_size"`
}

CollectorStats 收集器统计信息

type DevUI

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

DevUI 开发调试界面服务器

DevUI 提供了一个 Web 界面用于实时查看 Agent 执行过程,包括:

  • 实时事件流(SSE 推送)
  • REST API 查询历史事件和指标
  • Span 追踪可视化
  • 指标仪表板

使用示例:

ui := devui.New(devui.WithAddr("127.0.0.1:8080"))
defer func() {
    if err := ui.Stop(context.Background()); err != nil {
        log.Printf("Dev UI shutdown failed: %v", err)
    }
}()

ctx := hooks.ContextWithManager(context.Background(), ui.HookManager())
go func() {
    if err := ui.Start(); err != nil {
        log.Printf("Dev UI stopped: %v", err)
    }
}()
// 使用 ctx 执行 Agent,并访问 http://localhost:8080。

func New

func New(opts ...Option) *DevUI

New 创建 DevUI 实例

func (*DevUI) Addr

func (d *DevUI) Addr() string

Addr 返回监听地址

func (*DevUI) Collector

func (d *DevUI) Collector() *Collector

Collector 返回事件收集器

func (*DevUI) HookManager

func (d *DevUI) HookManager() *hooks.Manager

HookManager 返回 Hook Manager,用于注入到 Agent

func (*DevUI) IsRunning

func (d *DevUI) IsRunning() bool

IsRunning 返回服务器是否正在运行

func (*DevUI) Replay

func (d *DevUI) Replay() *ReplayManager

Replay 返回调试回放管理器

func (*DevUI) Start

func (d *DevUI) Start() error

Start 启动 DevUI 服务器 此方法会阻塞,建议在 goroutine 中调用

func (*DevUI) Stop

func (d *DevUI) Stop(ctx context.Context) error

Stop 停止 DevUI 服务器

func (*DevUI) Tracer

func (d *DevUI) Tracer() tracer.Tracer

Tracer 返回内置的 Tracer,用于注入到 Agent

func (*DevUI) URL

func (d *DevUI) URL() string

URL 返回完整的访问 URL

func (*DevUI) Uptime

func (d *DevUI) Uptime() time.Duration

Uptime 返回服务器运行时间

type DiffResult

type DiffResult struct {
	// SessionA 会话 A ID
	SessionA string `json:"session_a"`

	// SessionB 会话 B ID
	SessionB string `json:"session_b"`

	// StepDiffs 步骤差异
	StepDiffs []StepDiff `json:"step_diffs"`

	// Summary 差异摘要
	Summary string `json:"summary"`
}

DiffResult 执行差异

type ErrorData

type ErrorData struct {
	RunID   string `json:"run_id"`
	Source  string `json:"source"` // agent, llm, tool, retriever, graph
	Message string `json:"message"`
	Stack   string `json:"stack,omitempty"`
}

ErrorData 错误事件数据

type Event

type Event struct {
	// ID 事件唯一标识
	ID string `json:"id"`

	// Type 事件类型
	Type EventType `json:"type"`

	// Timestamp 事件发生时间
	Timestamp time.Time `json:"timestamp"`

	// TraceID 链路追踪 ID(可选)
	TraceID string `json:"trace_id,omitempty"`

	// SpanID Span ID(可选)
	SpanID string `json:"span_id,omitempty"`

	// ParentID 父 Span ID(可选)
	ParentID string `json:"parent_id,omitempty"`

	// AgentID Agent 标识(可选)
	AgentID string `json:"agent_id,omitempty"`

	// AgentName Agent 名称(可选)
	AgentName string `json:"agent_name,omitempty"`

	// Data 事件数据
	// 根据事件类型存储不同的数据结构
	Data map[string]any `json:"data"`
}

Event 统一事件结构

所有事件都使用此结构进行传输,通过 Type 字段区分事件类型, Data 字段存储事件特定数据。

func AcquireEvent

func AcquireEvent() *Event

AcquireEvent 从对象池获取事件对象

func (*Event) Clone

func (e *Event) Clone() *Event

Clone 克隆事件对象 用于需要保留事件副本的场景

func (*Event) Reset

func (e *Event) Reset()

Reset 重置事件对象到初始状态 用于对象池复用

type EventType

type EventType string

EventType 事件类型

const (
	// Agent 事件
	EventAgentStart EventType = "agent.start" // Agent 开始执行
	EventAgentEnd   EventType = "agent.end"   // Agent 执行结束

	// LLM 事件
	EventLLMRequest  EventType = "llm.request"  // LLM 请求开始
	EventLLMStream   EventType = "llm.stream"   // LLM 流式输出
	EventLLMResponse EventType = "llm.response" // LLM 响应完成

	// 工具事件
	EventToolCall   EventType = "tool.call"   // 工具调用开始
	EventToolResult EventType = "tool.result" // 工具返回结果

	// RAG 事件
	EventRetrieverStart EventType = "retriever.start" // 检索开始
	EventRetrieverEnd   EventType = "retriever.end"   // 检索结束

	// 图编排事件
	EventGraphStart EventType = "graph.start" // 图执行开始
	EventGraphNode  EventType = "graph.node"  // 图节点执行
	EventGraphEnd   EventType = "graph.end"   // 图执行结束

	// 状态事件
	EventStateChange EventType = "state.change" // 状态变更

	// 错误事件
	EventError EventType = "error" // 错误发生
)

type ExecutionResult

type ExecutionResult struct {
	// RunID 执行 ID
	RunID string `json:"run_id"`

	// GraphID 图定义 ID
	GraphID string `json:"graph_id"`

	// Status 执行状态: completed / failed
	Status string `json:"status"`

	// FinalState 最终状态
	FinalState map[string]any `json:"final_state"`

	// NodeResults 各节点的执行结果
	NodeResults []NodeResult `json:"node_results"`

	// DurationMs 总执行耗时(毫秒)
	DurationMs int64 `json:"duration_ms"`

	// Error 错误信息(如有)
	Error string `json:"error,omitempty"`
}

ExecutionResult 图执行结果

type GraphDefinition

type GraphDefinition struct {
	// ID 图定义的唯一标识
	ID string `json:"id"`

	// Name 图名称
	Name string `json:"name"`

	// Description 图描述(可选)
	Description string `json:"description,omitempty"`

	// Version 版本号,每次更新自增
	Version int `json:"version"`

	// Nodes 节点列表
	Nodes []GraphNodeDef `json:"nodes"`

	// Edges 边列表
	Edges []GraphEdgeDef `json:"edges"`

	// EntryPoint 入口节点 ID
	EntryPoint string `json:"entry_point"`

	// Metadata 元数据(可选)
	Metadata map[string]any `json:"metadata,omitempty"`

	// CreatedAt 创建时间
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt 最后更新时间
	UpdatedAt time.Time `json:"updated_at"`
}

GraphDefinition 可视化图定义

存储构建器画布上的图定义数据,包括节点、边和元数据。 该结构用于前后端之间的图定义序列化和持久化。

type GraphEdgeDef

type GraphEdgeDef struct {
	// ID 边的唯一标识
	ID string `json:"id"`

	// Source 源节点 ID
	Source string `json:"source"`

	// Target 目标节点 ID
	Target string `json:"target"`

	// Label 边的标签(可选,用于条件路由显示)
	Label string `json:"label,omitempty"`

	// Condition 条件表达式(可选,用于条件路由)
	Condition string `json:"condition,omitempty"`
}

GraphEdgeDef 图边定义

描述两个节点之间的连接关系,支持条件路由。

type GraphNodeData

type GraphNodeData struct {
	RunID    string         `json:"run_id"`
	GraphID  string         `json:"graph_id"`
	NodeID   string         `json:"node_id"`
	NodeName string         `json:"node_name"`
	State    map[string]any `json:"state,omitempty"`
	Duration int64          `json:"duration_ms,omitempty"` // 毫秒
}

GraphNodeData 图节点事件数据

type GraphNodeDef

type GraphNodeDef struct {
	// ID 节点唯一标识
	ID string `json:"id"`

	// Name 节点显示名称
	Name string `json:"name"`

	// Type 节点类型
	Type string `json:"type"`

	// Position 画布上的坐标位置
	Position Position `json:"position"`

	// Description 节点描述(可选)
	Description string `json:"description,omitempty"`

	// Config 节点配置(可选,按类型不同配置不同)
	Config map[string]any `json:"config,omitempty"`
}

GraphNodeDef 图节点定义

描述画布上的一个节点,包含节点类型、位置和配置。 支持的节点类型:

  • start: 开始节点
  • end: 结束节点
  • agent: Agent 节点
  • tool: 工具节点
  • condition: 条件分支节点
  • parallel: 并行节点
  • llm: LLM 调用节点

type GraphStore

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

GraphStore 图定义的内存存储

线程安全的内存存储,使用 sync.RWMutex 保护并发访问。 适用于 MVP 阶段,后续可替换为持久化存储。

func NewGraphStore

func NewGraphStore() *GraphStore

NewGraphStore 创建图定义存储

func (*GraphStore) Create

func (s *GraphStore) Create(def *GraphDefinition) *GraphDefinition

Create 创建新的图定义

自动生成 ID、设置版本号和时间戳。 返回创建后的图定义(包含生成的 ID)。

func (*GraphStore) Delete

func (s *GraphStore) Delete(id string) error

Delete 删除图定义

如果图不存在返回错误。

func (*GraphStore) Get

func (s *GraphStore) Get(id string) (*GraphDefinition, error)

Get 根据 ID 获取图定义

如果未找到返回 nil 和错误。

func (*GraphStore) List

func (s *GraphStore) List() []*GraphDefinition

List 列出所有图定义

返回所有图定义的切片,按创建时间倒序排列。

func (*GraphStore) Update

func (s *GraphStore) Update(id string, def *GraphDefinition) (*GraphDefinition, error)

Update 更新图定义

自增版本号并更新时间戳。 如果图不存在返回错误。

func (*GraphStore) Validate

func (s *GraphStore) Validate(def *GraphDefinition) *validationResult

Validate 验证图定义

执行以下校验:

  • 必须有 start 节点
  • 必须有 end 节点
  • 所有节点必须有 name
  • 边引用的节点必须存在
  • BFS 从入口点检查可达性
  • 检查孤立节点

type LLMRequestData

type LLMRequestData struct {
	RunID       string  `json:"run_id"`
	Provider    string  `json:"provider"`
	Model       string  `json:"model"`
	Messages    any     `json:"messages"`
	Temperature float64 `json:"temperature,omitempty"`
}

LLMRequestData LLM 请求事件数据

type LLMResponseData

type LLMResponseData struct {
	RunID            string `json:"run_id"`
	Model            string `json:"model"`
	Response         any    `json:"response"`
	PromptTokens     int    `json:"prompt_tokens"`
	CompletionTokens int    `json:"completion_tokens"`
	TotalTokens      int    `json:"total_tokens"`
	Duration         int64  `json:"duration_ms"` // 毫秒
}

LLMResponseData LLM 响应事件数据

type LLMStreamData

type LLMStreamData struct {
	RunID   string `json:"run_id"`
	Model   string `json:"model"`
	Content string `json:"content"`
	Index   int    `json:"index"`
}

LLMStreamData LLM 流式输出事件数据

type NodeResult

type NodeResult struct {
	// NodeID 节点 ID
	NodeID string `json:"node_id"`

	// NodeName 节点名称
	NodeName string `json:"node_name"`

	// NodeType 节点类型
	NodeType string `json:"node_type"`

	// Status 执行状态: completed / skipped / failed
	Status string `json:"status"`

	// DurationMs 执行耗时(毫秒)
	DurationMs int64 `json:"duration_ms"`

	// Output 节点输出
	Output map[string]any `json:"output,omitempty"`
}

NodeResult 单个节点的执行结果

type NodeTypeInfo

type NodeTypeInfo struct {
	// Type 节点类型标识
	Type string `json:"type"`

	// Name 显示名称
	Name string `json:"name"`

	// Description 类型描述
	Description string `json:"description"`

	// Icon 图标(emoji)
	Icon string `json:"icon"`

	// Color 主题颜色
	Color string `json:"color"`

	// Category 分类
	Category string `json:"category"`
}

NodeTypeInfo 节点类型信息

描述可用的节点类型,供前端节点面板使用。

type Option

type Option func(*Options)

Option 配置选项函数

func WithAPIPrefix

func WithAPIPrefix(prefix string) Option

WithAPIPrefix 设置 API 前缀

func WithAddr

func WithAddr(addr string) Option

WithAddr 设置监听地址

func WithAllowedOrigins

func WithAllowedOrigins(origins ...string) Option

WithAllowedOrigins 设置允许跨域访问的精确 Origin。非法值和 "*" 会被忽略。

func WithAuthToken

func WithAuthToken(token string) Option

WithAuthToken 设置 Builder 写端点所需的 bearer/CSRF token(至少 32 个无空白字节)。空值不会关闭认证:loopback 仍要求短期 session,非 loopback 会拒绝启动。

func WithCORS

func WithCORS(enabled bool) Option

WithCORS 设置是否启用 CORS

func WithMaxEvents

func WithMaxEvents(n int) Option

WithMaxEvents 设置最大事件缓存数

func WithMetrics

func WithMetrics(enabled bool) Option

WithMetrics 设置是否启用指标

func WithSSE

func WithSSE(enabled bool) Option

WithSSE 设置是否启用 SSE

func WithStaticDir

func WithStaticDir(dir string) Option

WithStaticDir 设置静态文件目录

func WithTimeouts

func WithTimeouts(read, write time.Duration) Option

WithTimeouts 设置超时时间

type Options

type Options struct {
	// Addr 监听地址,默认仅本机回环 "127.0.0.1:8080"
	Addr string

	// EnableSSE 是否启用 SSE 事件推送,默认 true
	EnableSSE bool

	// EnableMetrics 是否启用指标展示,默认 true
	EnableMetrics bool

	// StaticDir 自定义静态文件目录
	// 如果为空,使用内嵌的静态文件
	StaticDir string

	// MaxEvents 最大事件缓存数,默认 1000
	MaxEvents int

	// APIPrefix API 前缀,默认 "/api"
	APIPrefix string

	// CORSEnabled 是否启用 CORS,默认 false。启用时仍只允许 AllowedOrigins。
	CORSEnabled bool

	// AllowedOrigins 是允许跨域访问的精确 Origin 列表;不支持通配符。
	AllowedOrigins []string

	// AuthToken 是 Builder 写端点的 bearer/CSRF token。loopback 模式
	// 可为空并通过同源 bootstrap 建立短期 session;非 loopback 必须显式配置。
	AuthToken string

	// ReadTimeout HTTP 读取超时
	ReadTimeout time.Duration

	// WriteTimeout HTTP 写入超时
	WriteTimeout time.Duration
}

Options 配置选项

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions 返回默认配置

type Position

type Position struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

Position 画布坐标

type RateLimitMiddleware

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

RateLimitMiddleware 简单的速率限制中间件

func NewRateLimitMiddleware

func NewRateLimitMiddleware(limit int, window time.Duration) *RateLimitMiddleware

NewRateLimitMiddleware 创建速率限制中间件

func (*RateLimitMiddleware) Handler

func (m *RateLimitMiddleware) Handler(next http.Handler) http.Handler

Handler 返回中间件处理器

type ReplayManager

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

ReplayManager 调试回放管理器

提供执行历史的录制和回放功能,支持:

  • 自动录制每次图执行的完整过程
  • 按步骤回放执行过程(前进/后退)
  • 查看每步的状态快照
  • 比较不同执行的差异
  • 支持断点和条件断点

与 Collector 集成,自动从事件流中捕获执行数据。

func NewReplayManager

func NewReplayManager(maxSessions int) *ReplayManager

NewReplayManager 创建回放管理器

func (*ReplayManager) AddStep

func (m *ReplayManager) AddStep(sessionID string, step ReplayStep)

AddStep 添加执行步骤

func (*ReplayManager) CompareExecutions

func (m *ReplayManager) CompareExecutions(sessionA, sessionB string) (*DiffResult, error)

CompareExecutions 比较两次执行的差异

func (*ReplayManager) DeleteSession

func (m *ReplayManager) DeleteSession(sessionID string) error

DeleteSession 删除会话

func (*ReplayManager) EndRecording

func (m *ReplayManager) EndRecording(sessionID string, finalState map[string]any, err error)

EndRecording 结束录制

func (*ReplayManager) GetReplayState

func (m *ReplayManager) GetReplayState(sessionID string, stepIndex int) (*ReplayState, error)

GetReplayState 获取回放状态(在指定步骤)

func (*ReplayManager) GetSession

func (m *ReplayManager) GetSession(sessionID string) (*ReplaySession, error)

GetSession 获取会话详情

func (*ReplayManager) GetStep

func (m *ReplayManager) GetStep(sessionID string, stepIndex int) (*ReplayStep, error)

GetStep 获取指定步骤

func (*ReplayManager) ListSessions

func (m *ReplayManager) ListSessions() []*ReplaySession

ListSessions 列出所有会话

func (*ReplayManager) StartRecording

func (m *ReplayManager) StartRecording(runID, graphID, graphName string) string

StartRecording 开始录制一次执行

type ReplaySession

type ReplaySession struct {
	// ID 会话 ID
	ID string `json:"id"`

	// RunID 关联的执行 ID
	RunID string `json:"run_id"`

	// GraphID 关联的图 ID
	GraphID string `json:"graph_id,omitempty"`

	// GraphName 图名称
	GraphName string `json:"graph_name,omitempty"`

	// StartTime 开始时间
	StartTime time.Time `json:"start_time"`

	// EndTime 结束时间
	EndTime time.Time `json:"end_time,omitempty"`

	// Status 会话状态: recording / completed / failed
	Status string `json:"status"`

	// Steps 执行步骤列表(按时间排序)
	Steps []ReplayStep `json:"steps"`

	// FinalState 最终状态
	FinalState map[string]any `json:"final_state,omitempty"`

	// Error 错误信息(如有)
	Error string `json:"error,omitempty"`

	// Metadata 额外元数据
	Metadata map[string]any `json:"metadata,omitempty"`
}

ReplaySession 一次执行的录制会话

type ReplayState

type ReplayState struct {
	// SessionID 会话 ID
	SessionID string `json:"session_id"`

	// CurrentStep 当前步骤索引
	CurrentStep int `json:"current_step"`

	// TotalSteps 总步骤数
	TotalSteps int `json:"total_steps"`

	// IsPlaying 是否正在播放
	IsPlaying bool `json:"is_playing"`

	// Step 当前步骤详情
	Step *ReplayStep `json:"step,omitempty"`

	// Breakpoints 断点列表
	Breakpoints []Breakpoint `json:"breakpoints,omitempty"`
}

ReplayState 回放状态

type ReplayStep

type ReplayStep struct {
	// Index 步骤序号(从 0 开始)
	Index int `json:"index"`

	// Timestamp 时间戳
	Timestamp time.Time `json:"timestamp"`

	// Type 步骤类型: node_start, node_end, edge, condition, error
	Type string `json:"type"`

	// NodeID 相关节点 ID
	NodeID string `json:"node_id,omitempty"`

	// NodeName 节点名称
	NodeName string `json:"node_name,omitempty"`

	// NodeType 节点类型
	NodeType string `json:"node_type,omitempty"`

	// StateSnapshot 该步骤的状态快照
	StateSnapshot map[string]any `json:"state_snapshot,omitempty"`

	// Input 节点输入
	Input map[string]any `json:"input,omitempty"`

	// Output 节点输出
	Output map[string]any `json:"output,omitempty"`

	// DurationMs 步骤耗时
	DurationMs int64 `json:"duration_ms,omitempty"`

	// Message 步骤描述
	Message string `json:"message,omitempty"`
}

ReplayStep 执行步骤

type RetrieverEndData

type RetrieverEndData struct {
	RunID     string `json:"run_id"`
	Query     string `json:"query"`
	DocCount  int    `json:"doc_count"`
	Documents any    `json:"documents,omitempty"`
	Duration  int64  `json:"duration_ms"` // 毫秒
}

RetrieverEndData 检索结束事件数据

type RetrieverStartData

type RetrieverStartData struct {
	RunID string `json:"run_id"`
	Query string `json:"query"`
	TopK  int    `json:"top_k"`
}

RetrieverStartData 检索开始事件数据

type RingBuffer

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

RingBuffer 环形缓冲区 用于存储固定数量的最近事件

func NewRingBuffer

func NewRingBuffer(capacity int) *RingBuffer

NewRingBuffer 创建环形缓冲区

参数:

  • capacity: 缓冲区容量

func (*RingBuffer) Clear

func (rb *RingBuffer) Clear()

Clear 清空缓冲区

func (*RingBuffer) GetAll

func (rb *RingBuffer) GetAll() []*Event

GetAll 获取所有事件(从最旧到最新)

func (*RingBuffer) GetRecent

func (rb *RingBuffer) GetRecent(n int) []*Event

GetRecent 获取最近 n 个事件(从最新到最旧)

func (*RingBuffer) Push

func (rb *RingBuffer) Push(e *Event)

Push 添加事件到缓冲区 如果缓冲区已满,会覆盖最旧的事件

func (*RingBuffer) Size

func (rb *RingBuffer) Size() int

Size 返回当前事件数量

type SSEClient

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

SSEClient SSE 客户端 用于测试和程序化订阅

func NewSSEClient

func NewSSEClient(url string) *SSEClient

NewSSEClient 创建 SSE 客户端

func (*SSEClient) Close

func (c *SSEClient) Close()

Close 关闭连接

func (*SSEClient) Connect

func (c *SSEClient) Connect(ctx context.Context) error

Connect 连接到 SSE 服务器

func (*SSEClient) Errors

func (c *SSEClient) Errors() <-chan error

Errors 返回错误通道

func (*SSEClient) Events

func (c *SSEClient) Events() <-chan *Event

Events 返回事件通道

func (*SSEClient) IsConnected

func (c *SSEClient) IsConnected() bool

IsConnected 返回是否已连接

type Server

type Server struct {
	*http.Server
	// contains filtered or unexported fields
}

Server HTTP 服务器包装器 提供更精细的服务器生命周期控制

func NewServer

func NewServer(addr string, handler http.Handler) *Server

NewServer 创建 HTTP 服务器

func (*Server) ActualAddr

func (s *Server) ActualAddr() string

ActualAddr 返回实际监听地址

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning 返回服务器是否正在运行

func (*Server) Start

func (s *Server) Start() (string, error)

Start 启动服务器 返回实际监听的地址(当使用 :0 端口时有用)

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop 停止服务器

type StepDiff

type StepDiff struct {
	// StepIndex 步骤索引
	StepIndex int `json:"step_index"`

	// Field 差异字段
	Field string `json:"field"`

	// ValueA A 的值
	ValueA any `json:"value_a"`

	// ValueB B 的值
	ValueB any `json:"value_b"`
}

StepDiff 步骤差异

type ToolCallData

type ToolCallData struct {
	RunID    string         `json:"run_id"`
	ToolID   string         `json:"tool_id"`
	ToolName string         `json:"tool_name"`
	Input    map[string]any `json:"input"`
}

ToolCallData 工具调用事件数据

type ToolResultData

type ToolResultData struct {
	RunID    string `json:"run_id"`
	ToolID   string `json:"tool_id"`
	ToolName string `json:"tool_name"`
	Output   any    `json:"output"`
	Duration int64  `json:"duration_ms"` // 毫秒
	Error    string `json:"error,omitempty"`
}

ToolResultData 工具结果事件数据

Jump to

Keyboard shortcuts

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