loop

package
v0.3.8 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: GPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package loop 提供主事件循环,管理用户输入与程序状态流转

该包实现交互式循环的核心调度逻辑

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AIResponse

type AIResponse struct {
	MsgID           uint64
	ThinkingContext string
	Content         string
	Error           error
	SummaryText     string
	PendingTool     *[]funcs.ToolCall
	StopReason      StopReason
	ToolCallContent map[string]any
	Usage           *reqStructs.Usage
	SummaryFlag     bool
	AgentID         *string
}

AIResponse AI 响应

type Object

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

Object 循环对象

func New

func New(session *structs.Chats) *Object

New 创建一个新的循环对象

func (*Object) Approve

func (p *Object) Approve() error

Approve 审批待处理的工具调用,发送 msgActionApprove 指令到处理队列。 用户确认后执行工具调用,然后将结果继续发给 LLM。

func (*Object) Cancel

func (p *Object) Cancel()

Cancel 终止整个 Loop 生命周期(而非仅当前请求)。 调用后 Start() 主循环退出,所有等待中的消息被丢弃。

func (*Object) ChangeModel

func (p *Object) ChangeModel(modelID int) error

ChangeModel 切换当前会话使用的 AI 模型。 先验证模型 ID 有效性,再更新会话记录中的模型选择。

func (*Object) Chat

func (p *Object) Chat(msg string, refers []any) error

Chat 将用户消息发送到循环的处理队列。队列满时返回错误而非阻塞。 refers 参数用于消息引用(前端指定上下文片段)。

func (*Object) SetCallback

func (p *Object) SetCallback(callFunc func(AIResponse))

SetCallback 注册 AI 响应回调函数。在独立 goroutine 中循环读取 recvQueue, 将 AIResponse 对象传递给 UI 层进行处理。通过 recvSyncQueue 实现背压同步。

使用双 chan select 而非 busy-poll + sleep,idle 时 goroutine 挂起不消耗 CPU。

func (*Object) Start

func (p *Object) Start(ctx context.Context)

Start 启动 Demo Loop。主事件循环处理 AI 请求/响应的完整生命周期:

Idle → (用户输入) → Requesting → Reciving → WaitApprove
                                           ↓ (auto-reject)
                                           Idle ← (reject/approve)

needCompress 标志在 token 累积超过模型配置的压缩阈值后触发自动摘要

func (*Object) Stop

func (p *Object) Stop()

Stop 停止当前正在进行的操作,并标记 stopped 防止 AI 继续重试。

  • LLM 请求阶段:取消 responseCtx,终止流式响应。
  • 工具执行阶段: 1. 取消 toolCancelFunc,通过 session.GetContext() 通知 runCmd 等 kill 进程。 2. 调用 session.KillTool(),调用工具注册的直接停止回调(如 kill 进程)。
  • 空闲阶段:无操作(nothing to stop)。

注意:Stop 仅停止当前操作,不终止 Loop 主循环。Loop 存活以接收后续 prompt。

func (*Object) Summary

func (p *Object) Summary() error

Summary 请求对当前对话进行摘要压缩,发送 msgActionSummary 指令到处理队列。 用于在 token 数接近模型限制时清理上下文。

type StopReason

type StopReason uint8

StopReason 停止原因

const (
	// StopReasonNone 无
	StopReasonNone StopReason = iota
	// StopReasonModel 模型自行停止
	StopReasonModel
	// StopReasonUser 用户停止
	StopReasonUser
	// StopReasonError 错误
	StopReasonError
	// StopReasonPendingTool 等待工具调用
	StopReasonPendingTool
)

Jump to

Keyboard shortcuts

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