Documentation
¶
Overview ¶
Package chat 是 ihtml 的 AI 对话后端: 基于 CloudWeGo eino ADK, 通过语义工具直接增删改用户的 UI Item / 主题 / KV, 并把过程以流式事件 推回页面内核的对话抽屉。线格式与 casino admin AI 一致。
Index ¶
- Constants
- Variables
- func NewUserFacingError(message string) error
- type Backend
- type Config
- type ConfigError
- type ConfirmNonceStore
- type ModelOutputLimitError
- type RuntimeConfigOverride
- type RuntimeConfigProvider
- type RuntimeConfigRequest
- type TurnFailureKind
- type TurnObservation
- type TurnObservationPhase
- type TurnObserver
- type UserFacingError
Constants ¶
const ( ModelOutputLimitCallBytes = "call_bytes" ModelOutputLimitTurnBytes = "turn_bytes" ModelOutputLimitTurnEvents = "turn_events" ModelOutputLimitProviderResponseBytes = "provider_response_bytes" )
const ( ProviderOpenAI = "openai" ProviderClaude = "claude" AgentModeFast = "fast" AgentModeDeep = "deep" )
Provider 取值。openai 指一切 OpenAI 兼容端点(含各类网关/Ollama), claude 指 Anthropic 原生协议。
Variables ¶
var ErrInvalidConfig = errors.New("chat: invalid configuration")
ErrInvalidConfig is returned by Config.Validate and NewChecked when a programmatic chat configuration is not safe or internally consistent.
var ErrModelOutputLimit = errors.New("chat: model output limit exceeded")
ErrModelOutputLimit is the stable sentinel for a locally enforced model output boundary. It deliberately does not expose provider response content.
var ErrWriteRateLimited = errors.New("AI 写操作过于频繁,请稍后再试")
ErrWriteRateLimited 表示 AI 写工具触发了 Backend 级写限额。
Functions ¶
func NewUserFacingError ¶
NewUserFacingError 把已经过宿主审查的短文案标记为可展示错误。
Types ¶
type Backend ¶
type Backend struct {
// contains filtered or unexported fields
}
Backend 实现 ihtml.ChatBackend 与 ihtml.ModelLister。
func NewChecked ¶
NewChecked is the non-panicking, validation-first constructor recommended for SDK consumers. New remains available for source compatibility.
func (*Backend) Models ¶
Models 实现 ihtml.ModelLister。发现顺序与 casino 一致: 先查网关"已加载实例"(Ollama 风格 /ollama/api/ps → /api/ps, 目录里的模型 不等于能服务的模型), 查不到再退回 OpenAI 标准 GET /models 目录; claude 不提供模型发现, 返回空列表让前端手填。
func (*Backend) NewSession ¶
func (b *Backend) NewSession(_ context.Context, sctx *ihtml.ChatSessionContext) (ihtml.ChatSession, error)
NewSession 实现 ihtml.ChatBackend。
type Config ¶
type Config struct {
Provider string // openai / claude, 必填
BaseURL string // API 根地址, 必填(如 https://api.openai.com/v1)
APIKey string // OpenAI Bearer 或 Anthropic x-api-key;本地网关可留空
AuthToken string // Anthropic Authorization Bearer;仅 claude provider 使用
Model string // 默认模型;仅 AllowModelSelect=true 时允许前端另选
Stream bool // 流式输出, 建议 true
Thinking bool // 透出思考过程(需模型支持 reasoning)
RequestTimeout time.Duration // 单轮超时, 0 不限
MaxTokens int
// MaxProviderResponseBytes 是每次 provider HTTP 响应体的硬上限,
// 默认 8 MiB。它限制真实读取量,不依赖 provider 是否遵守 MaxTokens;
// 0 使用安全默认值,负数无效,不能关闭。
MaxProviderResponseBytes int64
// MaxModelOutputBytesPerCall / MaxModelOutputBytesPerTurn 分别限制单次
// 模型调用与整轮共享的输出字节。计入正文、reasoning 和 tool-call
// 字符串;默认 1 MiB / 4 MiB。0 用默认值,负数无效。
MaxModelOutputBytesPerCall int64
MaxModelOutputBytesPerTurn int64
// MaxModelOutputEventsPerTurn 限制整轮所有模型流 chunk 和非流响应数,
// 默认 4096,防止恶意 provider 用海量空/小 chunk 消耗 CPU。
MaxModelOutputEventsPerTurn int
// MaxAssistantMessageBytes 是最终可见回答快照的 UTF-8 字节上限,
// 默认 256 KiB。MaxReasoningBytesPerTurn 是整轮投影到客户端的
// reasoning 总上限,默认 256 KiB,且每个 segment 最多 64 KiB。
// 二者均会在超限时产生明确的截断标记;0 用默认值,负数无效。
MaxAssistantMessageBytes int64
MaxReasoningBytesPerTurn int64
// Temperature is the legacy non-zero override. Use TemperatureOverride when
// the provider must receive an explicit zero value.
Temperature float32
// TemperatureOverride, when non-nil, takes precedence over Temperature and
// preserves the distinction between "unset" and an explicit 0.
TemperatureOverride *float32
// ThinkingBudgetTokens 是 Claude extended thinking 的 token 预算。
// Thinking=true 且该值为 0 时使用 1024;MaxTokens 必须更大。
ThinkingBudgetTokens int
// RuntimeConfigProvider 可由宿主注入每轮生成参数覆盖。它只允许调整模型、
// thinking、token 与 temperature;网络、凭据、提示词、权限和预算仍由本
// Config 控制。实现必须支持并发调用。
RuntimeConfigProvider RuntimeConfigProvider
// SystemPrompt 追加在内置系统提示之后, 用于业务定制(如"你是某某产品的助手")。
SystemPrompt string
// ConfirmWrites 为 true 时所有中风险写操作也要人工确认。
// 无论此项为何值,高风险操作和可能安装 HTML/JS/CSS 的 Item 写入都会确认。
ConfirmWrites bool
// AllowUnconfirmedItemWrites 仅供完全信任模型和提示词的受控环境使用。
// 开启后,普通 ui_item_put 可不经人工确认直接执行;整体替换和回滚仍会确认。
AllowUnconfirmedItemWrites bool
// MaxIterations 是单轮的模型-工具循环上限, 默认 16。
MaxIterations int
// EnableDeepAgent 显式开放多 Agent 深度模式。默认关闭;客户端只有在该项
// 开启后才能为某轮请求 agent_mode=deep,空值始终走 fast。
EnableDeepAgent bool
// DisableDynamicToolSearch 关闭 Deep 模式默认启用的按需工具发现。
// Fast 始终直接绑定工具以保持低延迟;Deep 默认先通过 tool_search 选择
// 相关语义工具,避免把整个工具目录永久塞入每次模型调用。
DisableDynamicToolSearch bool
// DisableContextSummarization 关闭默认启用的安全会话压缩。压缩只作用于
// Agent 上下文,不改变业务数据,也不会给摘要模型开放工具。
DisableContextSummarization bool
// SummarizeAfterTokens / SummarizeAfterMessages 任一阈值超过时压缩历史。
// 0 分别使用 24000 tokens 与 80 条消息;只有明确关闭时才完全禁用。
SummarizeAfterTokens int
SummarizeAfterMessages int
// MaxModelCallsPerTurn 是根 Agent 与全部子 Agent 共享的模型调用上限,
// 默认 24;负数表示不限。fast 仍同时受 MaxIterations 限制。
MaxModelCallsPerTurn int
// MaxModelRetries 是每次 Agent 模型调用遇到瞬态网络、限流或上游错误时
// 的最大重试次数,默认 1;-1 禁用。认证、参数、策略与主动取消错误
// 永不重试,所有重试仍计入 MaxModelCallsPerTurn。
MaxModelRetries int
// MaxSubtasksPerTurn 是 Deep 模式每轮最多启动的只读子任务数,默认 3;
// 负数表示不限。fast 不启动子任务。
MaxSubtasksPerTurn int
// MaxToolCallsPerTurn 是根 Agent 与全部 Deep 子 Agent 共享的
// 语义工具调用总上限,默认 32;负数表示不限。内部计划与
// 子任务委派不计入,它们分别受计划校验和 MaxSubtasksPerTurn 约束。
MaxToolCallsPerTurn int
// MaxToolCallsPerTool 是单个语义工具每轮的调用上限,默认 8;
// 负数表示不限。
MaxToolCallsPerTool int
// MaxRepeatedToolCalls 是同一工具使用完全相同的规范化 JSON
// 参数可调用的次数,默认 2;负数表示不限。
MaxRepeatedToolCalls int
// MaxTurnDuration 是一轮(含全部子 Agent)的总墙钟预算,默认 2 分钟;
// 负数表示不限。若 RequestTimeout 更短,则采用更短值。
MaxTurnDuration time.Duration
// MaxOutstandingHostCallbacks 是单个 Backend 同时仍未真实返回的关键宿主
// 回调上限(RuntimeConfigProvider、拦截器与确认 nonce store),默认 32。
// 仅接受 0(默认)或 1..4096;TurnObserver 使用独立的观察池。
MaxOutstandingHostCallbacks int
// MaxOutstandingObservations 是单个 Backend 同时仍未真实返回的
// TurnObserver 回调上限,默认 32。观察过载时快照按 best-effort 丢弃,
// 不会占用关键宿主回调额度;仅接受 0(默认)或 1..4096。
MaxOutstandingObservations int
// MaxOutstandingOperations 是单个 Backend 同时仍未真实返回的模型流与
// Service 工具调用上限,默认 64;用于约束忽略 context 的第三方实现,
// 仅接受 0(默认)或 1..4096。
MaxOutstandingOperations int
// ConfirmSecret 是确认卡 HMAC 密钥。不设置则每进程随机。
// 固定密钥只保证跨实例验签;若确认卡还需跨重启/实例一次性核销,必须同时
// 配置共享的 ConfirmNonceStore。默认 nonce store 是进程内存态。
ConfirmSecret []byte
// ConfirmNonceStore 保存并原子核销确认 nonce。多副本部署应提供共享实现。
ConfirmNonceStore ConfirmNonceStore
// AllowModelSelect 为 true 时前端展示模型选择器。默认隐藏:
// 模型是运维概念;选择器隐藏时必须由 Config.Model 明确配置。
AllowModelSelect bool
// ProbeBaseURL 是 api_probe 唯一可信的目标源(如 https://app.internal)。
// 不配置时禁用探测;绝不会从客户端可控的 Request.Host 推导。
ProbeBaseURL string
// ProbeHTTPClient 可注入 mTLS、专用 Transport 等。其重定向策略会被安全
// 策略覆盖:只允许同源且仍命中 API 目录的重定向。
ProbeHTTPClient *http.Client
// ProbeForwardHeaders 是从 WebSocket 握手请求转发到探测请求的显式白名单。
// 默认不转发任何身份;如需当前会话身份,可明确加入 Cookie/Authorization。
ProbeForwardHeaders []string
// ProbeForwardQuery 是从握手 URL 转发的查询键白名单(例如旧系统的 uid)。
// 转发值会覆盖模型提供的同名 query,防止模型借该键冒充其他身份。
ProbeForwardQuery []string
// ProbeRequest 在发出探测前注入服务身份。inbound 是握手请求头的副本,
// outbound 是该探测请求的请求头;回调无法改写方法、URL、Host 或 Body。
ProbeRequest func(ctx context.Context, user string, inbound, outbound http.Header) error
// SessionStore 可替换默认的有界内存会话历史。自定义实现需要自行负责持久化、
// 容量限制和淘汰;默认实现支持 csid 重连并按以下四个上限淘汰。
SessionStore adk.SessionEventStore[*schema.Message]
// SessionNamespace 是宿主应用/租户的稳定命名空间。使用外部
// SessionStore 或 ConfirmNonceStore 时必须显式设置:它同时隔离持久化
// 历史与确认卡的应用域。它不会以明文写入 Store key。
SessionNamespace string
// SessionCapabilityVersion 是宿主在非结构化能力变化时主动递增的版本,
// 例如 ProbeRequest、WriteInterceptor 或自定义 Service 的授权语义改变。
// 版本变化会安全轮换历史作用域。
SessionCapabilityVersion string
// MaxHistorySessions 默认 128;负数表示不按会话数淘汰。
MaxHistorySessions int
// MaxHistoryEvents 默认每会话 256;负数表示不按事件数截断。
MaxHistoryEvents int
// MaxHistoryBytes 默认每会话 2 MiB;负数表示不按字节数截断。
MaxHistoryBytes int64
// HistoryTTL 默认 12 小时;负数表示不按空闲时间淘汰。
HistoryTTL time.Duration
// WritesPerMinute 是 chat 工具的独立写限额,避免工具调用绕过 HTTP 限流。
// 0 使用默认值 240,负数禁用。批量工具调用按一次写计数。
WritesPerMinute int
// WriteInterceptor 在每次真正执行写工具前调用,可接入共享配额/审计网关。
// 返回错误则拒绝该次写入。
WriteInterceptor func(ctx context.Context, user, tool string) error
// TurnInterceptor 在每轮模型调用前执行(限流/配额/计费检查)。普通错误
// 会被泛化;只有显式通过 NewUserFacingError 标记的安全文案才展示给用户。
TurnInterceptor func(ctx context.Context, user string) error
// TurnObserver 接收不含消息正文、工具参数和原始错误的结构化生命周期快照。
// 回调错误或 panic 不会改变对话结果;实现必须支持并发调用。
TurnObserver TurnObserver
}
Config 是对话后端配置。
type ConfigError ¶
ConfigError identifies the public configuration field that failed validation. Callers should use errors.As instead of matching Error strings.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
func (*ConfigError) Unwrap ¶
func (e *ConfigError) Unwrap() error
type ConfirmNonceStore ¶
type ConfirmNonceStore interface {
Put(ctx context.Context, nonce string, expiresAt time.Time) error
Consume(ctx context.Context, nonce string, now time.Time) (bool, error)
}
ConfirmNonceStore 持久化确认卡的一次性 nonce。Consume 必须以原子方式做到 “存在且未过期则删除并返回 true”,从而在多实例并发确认时仍最多执行一次。 多副本部署应使用共享数据库/缓存实现;默认实现仅在当前进程内有效。
type ModelOutputLimitError ¶
ModelOutputLimitError identifies which local model-output boundary rejected an otherwise successful provider response. Callers should use errors.As or errors.Is(err, ErrModelOutputLimit), not match Error text.
func (*ModelOutputLimitError) Error ¶
func (e *ModelOutputLimitError) Error() string
func (*ModelOutputLimitError) Unwrap ¶
func (e *ModelOutputLimitError) Unwrap() error
type RuntimeConfigOverride ¶
type RuntimeConfigOverride struct {
Model *string
Thinking *bool
ThinkingBudgetTokens *int
MaxTokens *int
Temperature *float32
}
RuntimeConfigOverride contains the only fields that may vary per turn. Pointer fields preserve the difference between "not overridden" and an explicit false/zero. Transport, credentials, prompts, tool permissions, client model-selection policy and safety budgets always remain authoritative in Config and cannot be changed here.
type RuntimeConfigProvider ¶
type RuntimeConfigProvider interface {
ResolveTurnConfig(ctx context.Context, request RuntimeConfigRequest) (RuntimeConfigOverride, error)
}
RuntimeConfigProvider resolves trusted, host-controlled generation settings immediately before a model is constructed for a turn. Implementations may consult any host-owned configuration source and must be safe for concurrent calls from independent sessions.
The request intentionally excludes prompts, message bodies, credentials and provider URLs. Model is the effective model after the server has validated any allowed client selection; the trusted provider may replace it. Returning an error rejects the turn without exposing that error to the browser.
type RuntimeConfigRequest ¶
type RuntimeConfigRequest struct {
User string
SessionID string
AgentMode string
ToolsEnabled bool
Model string
Thinking bool
ThinkingBudgetTokens int
MaxTokens int
Temperature *float32
}
RuntimeConfigRequest is the minimal trusted context supplied to a RuntimeConfigProvider. User is the authenticated host identity; SessionID is an opaque, hashed identifier and does not contain User or the browser csid.
type TurnFailureKind ¶
type TurnFailureKind string
TurnFailureKind is a content-free failure category suitable for metrics.
const ( TurnFailureNone TurnFailureKind = "" TurnFailureCanceled TurnFailureKind = "canceled" TurnFailureTimeout TurnFailureKind = "timeout" TurnFailureRejected TurnFailureKind = "rejected" TurnFailureConfiguration TurnFailureKind = "configuration" TurnFailureInternal TurnFailureKind = "internal" )
type TurnObservation ¶
type TurnObservation struct {
Phase TurnObservationPhase
Sequence int
RunID string
TurnID string
SessionID string
AgentMode string
Provider string
Model string
ToolsEnabled bool
StartedAt time.Time
FinishedAt time.Time
Duration time.Duration
ModelCalls int64
Subtasks int64
ToolCalls int64
OutputBytes int64
Streamed bool
FinishReason string
Usage *ihtml.ChatUsage
Repaired bool
FailureKind TurnFailureKind
}
TurnObservation is a privacy-preserving turn snapshot. It deliberately carries no user identity, prompt, message/reasoning content, tool name or arguments, model response, provider URL, credential, or raw error. Hosts that need content-level audit must add it explicitly at their own trust boundary.
type TurnObservationPhase ¶
type TurnObservationPhase string
TurnObservationPhase identifies one immutable lifecycle snapshot.
const ( TurnObservationStarted TurnObservationPhase = "started" TurnObservationCompleted TurnObservationPhase = "completed" TurnObservationFailed TurnObservationPhase = "failed" )
type TurnObserver ¶
type TurnObserver interface {
ObserveTurn(ctx context.Context, observation TurnObservation) error
}
TurnObserver receives best-effort lifecycle snapshots. Accepted snapshots are ordered per turn (started before completed/failed), but overload or a callback that does not return after its context ends may cause later snapshots to be dropped. Delivery is asynchronous and uses a pool isolated from critical host callbacks, so a slow exporter cannot block or reject the model turn. One observer may be called concurrently by different sessions and must be thread-safe. Returned errors and panics are isolated from the model turn.
type UserFacingError ¶
UserFacingError 是宿主明确声明可安全展示给终端用户的错误。不得把底层 HTTP/SQL/凭据/堆栈错误直接实现为该接口;普通 error 会被统一泛化。
Source Files
¶
- budget.go
- chat.go
- collect.go
- config_validate.go
- confirm.go
- confirm_cancel.go
- confirmation_failure.go
- context_summary.go
- deep.go
- govern.go
- history.go
- host_callback_limiter.go
- inspect.go
- model.go
- model_output_size.go
- model_retry.go
- operation_limiter.go
- prompt.go
- reply_repair.go
- runtime_extensions.go
- scoped_adapter.go
- session_owner.go
- session_scope.go
- session_store_guard.go
- session_work.go
- template_tools.go
- tool_argument_hash.go
- tool_payload_guard.go
- tools.go