assistant

package
v1.0.0-rc.34 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package assistant 是 pt-tools 内置的 AI 助手(路线图 M19):经 OpenAI 兼容的 Chat Completions 接口(官方 openai-go) 调大模型,工具是每次运行在进程内连上的 MCP 服务(internal/mcp 的同一套工具,经 App API v1 执行)。

Service 是运行、待确认操作与保留期清理的唯一所有者:

  • 每个会话同时只有一次运行,运行在后台;进度经事件流(递增序号)交给网页(SSE)、App(长轮询)与 ChatOps;
  • 写工具不让模型自己确认:给模型的参数里没有 confirm,每个写操作建一条待确认记录,结论只经数据库条件更新得出, 批准了才带 confirm=true 调用一次;
  • 落库与下发的只有脱敏以后的内容,模型给的原始参数只在运行的内存里。

Index

Constants

View Source
const (
	// EventRunStarted 是一次运行开始
	EventRunStarted = "run_started"
	// EventDelta 是模型回答的一段文字(只在内存里,最终的回答另有 EventMessage)
	EventDelta = "delta"
	// EventMessage 是落库的一条消息:用户的、模型的(含工具调用)、工具结果、提示
	EventMessage = "message"
	// EventToolStarted 是开始执行一个工具
	EventToolStarted = "tool_started"
	// EventConfirmation 是待确认操作建好了或者有了结论
	EventConfirmation = "confirmation"
	// EventRunFinished 是运行结束:Status 是 done、canceled 或 failed
	EventRunFinished = "run_finished"
)

事件的种类。

View Source
const (
	RunDone     = "done"
	RunCanceled = "canceled"
	RunFailed   = "failed"
)

运行结束的状态。

View Source
const (
	DefaultMaxSteps       = 8
	DefaultConfirmMinutes = 10
	DefaultRetentionDays  = 30
)

设置的默认值与取值范围。

Variables

View Source
var (
	ErrDisabled  = errors.New("AI 助手没有启用或没有配置好")
	ErrNotFound  = errors.New("会话或操作不存在")
	ErrBusy      = errors.New("这个会话正在回答:等它结束或先停止")
	ErrTooMany   = errors.New("同时进行的回答太多,稍后再试")
	ErrInvalid   = errors.New("参数不对")
	ErrForbidden = errors.New("没有确认改动类操作的权限")
	ErrDecided   = errors.New("这个操作已经处理过了")
	ErrClosed    = errors.New("AI 助手正在关闭")
)

对外的错误(web 按它们选状态码)。

Functions

This section is empty.

Types

type Actor

type Actor struct {
	Owner string
	// Entry 是入口:models.AssistantEntryWeb、AssistantEntryApp、AssistantEntryChatOps
	Entry string
	// Name 是显示名(记进审计的参数)
	Name string
	// CanWrite 为假时模型拿不到写工具,也不能确认写操作
	CanWrite bool
	// Notify 不为空时,运行把消息、待确认、确认结论与结束交给它(ChatOps 经它异步回复);文字增量不给。
	// 关机取消的运行不再调用它。
	Notify func(ctx context.Context, ev Event)
}

Actor 是用助手的一方。Owner 是带命名空间的属主:web:<用户名>、token:<令牌编号>、device:<设备编号>、chatops:<绑定编号>; 会话一律按属主过滤,别人的会话当作不存在。

type ChatOpsHandler

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

ChatOpsHandler 把通知渠道里绑定用户的非命令消息交给助手(实现 chatops.AssistantHandler 与 /newchat 的 AssistantService):

  • 每个绑定一个滚动会话(属主 chatops:<绑定编号>),/newchat 开新的;
  • 有待确认的操作时,下一条非命令消息由这里解读:「确认」经条件更新批准,别的内容一律拒绝;
  • 只登记、立即返回,回答、确认提示、超时提示都由后台运行经 Replier 发出;
  • 不是管理员的绑定拿不到改动类工具。

func NewChatOpsHandler

func NewChatOpsHandler(svc *Service, replier ChatOpsReplier) *ChatOpsHandler

NewChatOpsHandler 建处理器。

func (*ChatOpsHandler) Enabled

func (h *ChatOpsHandler) Enabled(ctx context.Context) bool

Enabled 报告助手启用了、接口配好了、ChatOps 开关也打开了。

func (*ChatOpsHandler) Handle

Handle 处理一条非命令消息。返回立即回复与审计结果。

func (*ChatOpsHandler) NewChat

func (h *ChatOpsHandler) NewChat(ctx context.Context, src chatops.Source) error

NewChat 给这个绑定开一个新会话(/newchat)。

func (*ChatOpsHandler) SetTemplates

func (h *ChatOpsHandler) SetTemplates(t *notify.Templates)

SetTemplates 接上消息模板(在接到 ChatOps 以前调用)。

type ChatOpsReplier

type ChatOpsReplier interface {
	Reply(ctx context.Context, msg notify.InboundMessage, reply chatops.Reply) error
}

ChatOpsReplier 是 ChatOps 的回复出口(cmd 的 liveNotifyManager:按消息来源的通道配置找到在线的通道发送)。

type Cipher

type Cipher interface {
	Encrypt(plain string) (string, error)
	Decrypt(enc string) (string, error)
}

Cipher 加解密 API Key 与代理地址(生产环境是 ConfigStore 的 EncryptCookie / DecryptCookie)。

type Config

type Config struct {
	DB     *gorm.DB
	Cipher Cipher
	Tools  ToolServer
	// ResolveURL 把种子下载地址解析成站点与种子编号(v2.TrackerResolver.ResolveDownloadURL):用户贴的地址与 push_torrent
	// 的 torrent_url 在交给模型、建待确认以前先换掉,passkey 不出 pt-tools
	ResolveURL func(rawURL string) (site, torrentID string, ok bool)
	// Version 是 pt-tools 的版本(MCP 客户端的实现信息)
	Version string
	// Now 为空时用 time.Now(测试里换掉)
	Now func() time.Time
	// HTTPClient 不为空时用它调模型(测试用;设置里的代理不再生效)
	HTTPClient *http.Client
}

Config 是服务的依赖。

type ConfirmationView

type ConfirmationView struct {
	ID         uint   `json:"id"`
	RunID      string `json:"run_id"`
	ToolCallID string `json:"tool_call_id"`
	Tool       string `json:"tool"`
	// Summary 是给人看的一句话(例如「暂停种子:下载器 #1,任务 abc」)
	Summary   string         `json:"summary"`
	Arguments map[string]any `json:"arguments"`
	Status    string         `json:"status"`
	DecidedBy string         `json:"decided_by,omitempty"`
	DecidedAt *time.Time     `json:"decided_at,omitempty"`
	ExpiresAt time.Time      `json:"expires_at"`
	CreatedAt time.Time      `json:"created_at"`
}

ConfirmationView 是一个待确认操作。

type ConversationDetail

type ConversationDetail struct {
	ConversationView
	Messages      []MessageView      `json:"messages"`
	Confirmations []ConfirmationView `json:"confirmations"`
	// RunID 是进行中的运行(没有时为空)
	RunID string `json:"run_id,omitempty"`
	// Partial 是进行中的运行到现在的回答文字
	Partial string `json:"partial,omitempty"`
	// LastSeq 是读事件的 after:从它接着读不会漏
	LastSeq int64 `json:"last_seq"`
}

ConversationDetail 是一个会话:消息、待确认操作,以及接着读事件用的位置。

type ConversationView

type ConversationView struct {
	ID        uint      `json:"id"`
	Title     string    `json:"title"`
	Entry     string    `json:"entry"`
	Running   bool      `json:"running"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

ConversationView 是会话列表里的一项。

type Event

type Event struct {
	Seq   int64  `json:"seq"`
	Type  string `json:"type"`
	RunID string `json:"run_id,omitempty"`
	// Text 是 delta 的文字;Replace 为真时它是到现在的全部回答文字(脱敏改了已经发出去的部分),整段替换
	Text         string            `json:"text,omitempty"`
	Replace      bool              `json:"replace,omitempty"`
	Message      *MessageView      `json:"message,omitempty"`
	Tool         *ToolCallView     `json:"tool,omitempty"`
	Confirmation *ConfirmationView `json:"confirmation,omitempty"`
	// Status 是 run_finished 的结束状态
	Status string    `json:"status,omitempty"`
	Error  string    `json:"error,omitempty"`
	At     time.Time `json:"at"`
}

Event 是会话事件流里的一个事件。Seq 在这个进程里递增,重启以后的序号一定比重启前的大。

type EventPage

type EventPage struct {
	Events []Event `json:"events"`
	// Reset 为真表示中间的事件已经丢了(或者 pt-tools 重启过):重新读一遍会话,从它的 last_seq 接着读
	Reset bool `json:"reset"`
	// Last 是下次读的 after
	Last    int64 `json:"last"`
	Running bool  `json:"running"`
}

EventPage 是一次读事件的结果。

type MessageView

type MessageView struct {
	ID        uint           `json:"id"`
	RunID     string         `json:"run_id,omitempty"`
	Role      string         `json:"role"`
	Content   string         `json:"content"`
	ToolCalls []ToolCallView `json:"tool_calls,omitempty"`
	// ToolName、ToolCallID 是工具结果对应的调用
	ToolName   string    `json:"tool_name,omitempty"`
	ToolCallID string    `json:"tool_call_id,omitempty"`
	IsError    bool      `json:"is_error,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
}

MessageView 是一条消息(脱敏以后的)。

type ModelList

type ModelList struct {
	Models []string `json:"models"`
	// Total 是服务商列出的模型数(去掉之前)
	Total int `json:"total"`
}

ModelList 是服务商 GET /models 列出的模型去掉嵌入、语音、图像这类以后剩下的,给设置页的模型下拉框。 按名字判断,不保证每个都支持 Chat Completions 与工具调用(选好以后测试连接)。

type SendResult

type SendResult struct {
	RunID   string      `json:"run_id"`
	Message MessageView `json:"message"`
}

SendResult 是发消息的结果:后台运行的编号与落库的用户消息。

type Service

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

Service 是 AI 助手服务。

func New

func New(cfg Config) *Service

New 建服务。Start 以后才清理保留期外的会话。

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, a Actor, convID uint) error

Cancel 停止会话进行中的运行(没有时什么也不做):在等确认的操作标成过期,不执行。

func (*Service) Cleanup

func (s *Service) Cleanup(ctx context.Context) (int, error)

Cleanup 删掉保留期外(updated_at 早于现在减保留天数)、没有进行中运行的会话;保留天数为 0 时不清理。返回删了几个。

func (*Service) Close

func (s *Service) Close(ctx context.Context) error

Close 停收新的运行,取消进行中的运行并在 ctx 的时限内等它们退出(含关掉 MCP 会话),最后把待确认标成过期。

func (*Service) Conversation

func (s *Service) Conversation(ctx context.Context, a Actor, id uint) (ConversationDetail, error)

Conversation 读一个会话:最近的消息、待确认操作与接着读事件的位置。

func (*Service) Conversations

func (s *Service) Conversations(ctx context.Context, a Actor) ([]ConversationView, error)

Conversations 列出属主的会话,最近的在前。

func (*Service) CreateConversation

func (s *Service) CreateConversation(ctx context.Context, a Actor, title string) (ConversationView, error)

CreateConversation 建一个会话。标题为空时用第一条消息的开头。

func (*Service) Decide

func (s *Service) Decide(ctx context.Context, a Actor, id uint, approve bool) (ConfirmationView, error)

Decide 是属主确认(approve 为真)或拒绝一个待确认操作。别人的当作不存在;不能写的主体回 ErrForbidden; 已经有结论的(含同时点的另一次)回 ErrDecided 与现在的状态。

func (*Service) DeleteConversation

func (s *Service) DeleteConversation(ctx context.Context, a Actor, id uint) error

DeleteConversation 删掉会话连同消息与待确认记录;正在回答的回 ErrBusy。

func (*Service) Events

func (s *Service) Events(ctx context.Context, a Actor, convID uint, after int64, wait time.Duration) (EventPage, error)

Events 读会话 after 以后的事件,没有时最多等 wait(上限 30 秒)。

func (*Service) LatestConversation

func (s *Service) LatestConversation(ctx context.Context, a Actor) (ConversationView, bool, error)

LatestConversation 是属主最近建的会话(ChatOps 的滚动会话);没有时 ok 为假。按建的先后(编号)选,不按更新时间: 开了新会话以后,旧会话里还在跑的回答结束时会更新旧会话的时间,下一条消息也不能回到旧会话。

func (*Service) ListModels

func (s *Service) ListModels(ctx context.Context, in SettingsInput) (ModelList, error)

ListModels 按输入(还没保存的也行)读服务商的模型列表。Key 的规则同 TestSettings:输入没给 Key 时用存着的, 但接口地址变了就不带。模型可以还没选,接口地址要有。

func (*Service) PendingConfirmation

func (s *Service) PendingConfirmation(ctx context.Context, a Actor) (ConfirmationView, bool, error)

PendingConfirmation 是属主最近一个还在等的待确认操作(ChatOps 用它解读回复);没有时 ok 为假。

func (*Service) SaveSettings

func (s *Service) SaveSettings(ctx context.Context, in SettingsInput) (Settings, error)

SaveSettings 保存设置。

func (*Service) Send

func (s *Service) Send(ctx context.Context, a Actor, convID uint, text string) (SendResult, error)

Send 往会话里发一条消息并在后台开始回答,立即返回。同一个会话同时只有一次运行(另一个回 ErrBusy)。

func (*Service) Settings

func (s *Service) Settings(ctx context.Context) (Settings, error)

Settings 读设置。

func (*Service) Start

func (s *Service) Start(ctx context.Context) error

Start 把上次留下的待确认标成过期(运行不跨重启),再起每天一次的保留期清理。

func (*Service) Status

func (s *Service) Status(ctx context.Context, a Actor) (Status, error)

Status 读状态。

func (*Service) TestSettings

func (s *Service) TestSettings(ctx context.Context, in SettingsInput) (TestResult, error)

TestSettings 按输入(还没保存的也行)发一次很短的对话,看接口地址、模型与 Key 能不能用。 输入没给 Key 时用存着的 Key,但接口地址变了就不带:存着的 Key 只发到保存它时的地址。

type Settings

type Settings struct {
	Enabled  bool   `json:"enabled"`
	Provider string `json:"provider"`
	BaseURL  string `json:"base_url"`
	Model    string `json:"model"`
	// HasAPIKey 报告存没存 API Key
	HasAPIKey      bool   `json:"has_api_key"`
	ProxyURL       string `json:"proxy_url"`
	ChatOps        bool   `json:"chatops"`
	MaxSteps       int    `json:"max_steps"`
	ConfirmMinutes int    `json:"confirm_minutes"`
	// RetentionDays 是会话保留几天,0 表示不清理
	RetentionDays int `json:"retention_days"`
}

Settings 是界面上看到的设置:API Key 只写不读(只回有没有),代理地址里的密码换成 ***。

type SettingsInput

type SettingsInput struct {
	Enabled        bool    `json:"enabled"`
	Provider       string  `json:"provider"`
	BaseURL        string  `json:"base_url"`
	Model          string  `json:"model"`
	APIKey         *string `json:"api_key,omitempty"`
	ProxyURL       *string `json:"proxy_url,omitempty"`
	ChatOps        bool    `json:"chatops"`
	MaxSteps       int     `json:"max_steps"`
	ConfirmMinutes int     `json:"confirm_minutes"`
	RetentionDays  *int    `json:"retention_days,omitempty"`
}

SettingsInput 是保存设置的参数。APIKey、ProxyURL 为 nil 时不改,为空串时清除;ProxyURL 与读到的(密码换成 *** 的) 地址相同时也不改。改了接口地址又没给新的 API Key 时,存着的 Key 清掉:Key 不会发到保存它时以外的地址。 MaxSteps、ConfirmMinutes 为 0 时用默认值;RetentionDays 为 nil 时不改。

type Status

type Status struct {
	Enabled    bool   `json:"enabled"`
	Model      string `json:"model"`
	CanConfirm bool   `json:"can_confirm"`
	// ChatOps 报告通知渠道里的非命令消息交不交给助手
	ChatOps bool `json:"chatops"`
}

Status 是给各入口看的状态:启用没有、用的模型、这个主体能不能确认改动类操作。不含 Key 与接口地址。

type TestError

type TestError struct{ Message string }

TestError 是测试连接没通:Message 是给人看的原因(不带 Key)。

func (*TestError) Error

func (e *TestError) Error() string

type TestResult

type TestResult struct {
	Model     string `json:"model"`
	Reply     string `json:"reply"`
	LatencyMs int64  `json:"latency_ms"`
}

TestResult 是测试连接的结果。

type ToolCallView

type ToolCallView struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	// Write 报告是不是改动类操作(要确认)
	Write bool `json:"write,omitempty"`
}

ToolCallView 是模型的一个工具调用:参数是规范化脱敏以后的 JSON。

type ToolServer

type ToolServer func(c mcp.Caller) *sdk.Server

ToolServer 建一次运行用的 MCP 服务(web.Server.AssistantToolServer):调用方固定成 c,审计通道是 assistant。

Jump to

Keyboard shortcuts

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