llm

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

本文件复刻官方 packages/llm/llm/src/assembler.ts 的核心算法,适配本项目简化版 StreamChunk 协议(text/reasoning/tool-call/done)。

Agent 循环一遍接收流式分片、一遍把原始分片写入日志,BlockAssembler 是唯一权威的 "分片 → 助手消息"组装算法:连续 text/reasoning 增量合并,tool-call 在到达时固化为 工具使用块,最终输出严格保持流顺序。

本文件对应任务 N01:DeepSeek Prefix Cache 探针埋点(阶段 0 前置基础设施)。

对齐上游:DeepSeek API docs(KV cache)+ 本地衍生。

设计要点:

  • CacheStats 聚合每请求的 prompt_cache_hit_tokens / prompt_cache_miss_tokens;
  • ComputeHitRatio() 计算命中率 = hit/(hit+miss),在总量为 0 或全命中/全未命中时 都能给出确定值(防 0/0 → NaN);
  • CacheLogLine 生成每次 LLM 请求日志行所需字段 cache.hit_ratio=..., 供观测/告警(N08)与 N 簇全部验收作为数据基线。

本文件对应 code-review 修复点 R05:对齐官方 @deepseek-ai/omnix-llm/error 的 errorChain()。

对照上游:D:\workspace\python_workspace\deepseek-harness\packages\llm\llm\src\error.ts

  • `export function errorChain(value): string` —— 从最外层 message 开始,把完整 cause 链与 AggregateError 成员渲染成等价语义的字符串;wrapper 若与 cause 逐字相同则不重复渲染; 带循环防护(active path set,仅真环被折叠为 <circular cause>,共享 cause 仍完整展开)。

Go 侧等价物(本项目此前无此公共工具):

  • RenderErrorChain(v any) string:把任意 error / 带 .message 的普通值渲染成可读错误链;
  • 支持 Go 标准库的单一 cause(errors.Unwrap / interface{ Unwrap() error })与 AggregateError 等价物(errors.Join → interface{ Unwrap() []error },成员以 ` [a; b]` 括起);
  • 循环防护:渲染路径上重复的 error 折叠为 <circular cause>;共享 cause(菱形)仍完整展开。

Package llm 提供 LLM Provider 接缝与流式协议类型。

对齐上游:packages/llm/llm + providers

设计要点:

  • LLMAdapter 是统一的模型调用接口(Chat 流式 + 用量回调);
  • Message/ContentBlock 覆盖 text/tool_use/tool_result/image 四类内容块;
  • StreamChunk 承载 text / reasoning / tool-call / done 流式分片;
  • LlmFailure 对模型侧错误做稳定分类(overload / rate-limit / response-refusal / context-overflow / quota / empty-response / invalid-credential),供重试(S15)与 request-error 瀑布(M34)消费;分类器对齐官方 error.ts 的 provider 文本判别语义。

本文件对应任务 S15:LLM Retry(指数退避 + 抖动 + 写 llm/retry 事件)。

对齐上游:packages/llm/llm retry middleware

设计要点:

  • RetryMiddleware 包裹任意 LLMAdapter,仅在可重试失败(overload / rate-limit)上 做指数退避重试;response-refusal / context-overflow 不重试,直接上抛;
  • 每次退避后写一条 llm/retry 事件(attempt / backoffMs / error),供审计与决策;
  • 达到最大尝试次数仍未成功 → 携最后一次错误上抛,交由上层 M34 request-error 瀑布接续处理(本层不无限重试)。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CacheLogLine

func CacheLogLine(u Usage) string

CacheLogLine 生成一次请求日志行的命中率字段("cache.hit_ratio=0.95")。 用于每次 LLM 请求日志行;作为 N01 验收的采集基线。

func HitRatioOf

func HitRatioOf(u Usage) float64

HitRatioOf 从一次 llm.Usage 直接求命中率(便捷方法)。

func RenderErrorChain

func RenderErrorChain(v any) string

RenderErrorChain 把任意抛出值渲染为带完整 cause 链的错误串。

语义对齐官方 error.ts 的 errorChain():

  • error:取 Error(),空则回落类型名;
  • 非 error:取结构体的 message (Message) 字段,否则原样字符串化;
  • AggregateError 成员:以 " [成员1; 成员2]" 括起追加;
  • 单一 cause:以 ": " 追加,若与 wrapper message 逐字相同则跳过;
  • 仅作为诊断展示用途(消息/日志/通知),绝不用其结果做业务路由——路由一律走稳定 Kind/code。

Types

type Alert

type Alert struct {
	// Level 级别。
	Level AlertLevel `json:"level"`
	// Message 告警内容(含 session.id / current / previous)。
	Message string `json:"message"`
	// Webhook 是否应触发 webhook 通知(连续破窗时)。
	Webhook bool `json:"webhook,omitempty"`
}

Alert 是一次缓存破窗告警。

type AlertLevel

type AlertLevel string

AlertLevel 是告警级别。

const (
	AlertWarn  AlertLevel = "warn"
	AlertError AlertLevel = "error"
)

告警级别。

type AlertSink

type AlertSink func(a Alert)

AlertSink 是告警输出回调(日志/webhook)。

type BlockAssembler

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

BlockAssembler 增量地把 StreamChunk 组装为 ContentBlock。 零值不可用,请用 NewBlockAssembler。

func NewBlockAssembler

func NewBlockAssembler() *BlockAssembler

NewBlockAssembler 创建空组装器。

func (*BlockAssembler) Blocks

func (a *BlockAssembler) Blocks() []ContentBlock

Blocks 返回截至目前组装好的块(拷贝,保持流顺序);未结束的打开缓冲也会被组装。

func (*BlockAssembler) Finished

func (a *BlockAssembler) Finished() bool

Finished 是否已收到 done。

func (*BlockAssembler) Message

func (a *BlockAssembler) Message() Message

Message 用组装好的块构造一条助手消息。

func (*BlockAssembler) Push

func (a *BlockAssembler) Push(c StreamChunk)

Push 按流顺序喂入一个分片。

type CacheAlert

type CacheAlert struct {
	// Threshold 低命中率阈值(默认 0.5)。
	Threshold float64
	// DropWarn 单次相对骤降阈值(默认 0.3)。
	DropWarn float64
	// ConsecutiveFails 连续低于阈值触发 error 的次数(默认 5)。
	ConsecutiveFails int
	// Sink 告警输出。
	Sink AlertSink
	// contains filtered or unexported fields
}

CacheAlert 检测缓存命中率破窗并分级告警。

  • 单次命中率突降 > DropWarn 相比上一次 → warn(记录 session/current/previous);
  • 连续 consecutiveFails 次命中率 < Threshold → error + 可选 webhook;
  • 命中率恢复(≥ Threshold)→ consecutiveFails 重置为 0。

func NewCacheAlert

func NewCacheAlert(sink AlertSink) *CacheAlert

NewCacheAlert 创建默认配置的破窗告警。

func (*CacheAlert) Alerts

func (a *CacheAlert) Alerts() []Alert

Alerts 返回累计告警快照。

func (*CacheAlert) Observe

func (a *CacheAlert) Observe(sessionID string, ratio float64)

Observe 记录一次命中率并判定是否告警。 sessionID 用于告警上下文。

type CacheStats

type CacheStats struct {
	// HitTokens 命中缓存的 prompt token 数。
	HitTokens int `json:"hitTokens"`
	// MissTokens 未命中缓存的 prompt token 数。
	MissTokens int `json:"missTokens"`
}

CacheStats 是一次或累计的 prefix cache 用量聚合。

func (*CacheStats) Add

func (c *CacheStats) Add(hit, miss int)

Add 累加一次用量。

func (*CacheStats) ComputeHitRatio

func (c *CacheStats) ComputeHitRatio() float64

ComputeHitRatio 计算命中率,防 0/0×NaN:

  • 总量为 0 → 0.0;全命中 → 1.0;全未命中 → 0.0;部分命中 → hit/total。

func (*CacheStats) RecordUsage

func (c *CacheStats) RecordUsage(u Usage)

RecordCacheUsage 简便地把一次用量记入累计 stats(供 tokenmeter/观测聚合)。

func (*CacheStats) Total

func (c *CacheStats) Total() int

Total 返回总 prompt token(hit + miss)。

type ChatRequest

type ChatRequest struct {
	// ReasoningEffort is an explicit, provider-owned reasoning setting.
	ReasoningEffort string `json:"reasoningEffort,omitempty"`
	// Model 模型名(如 deepseek-chat)。
	Model string `json:"model"`
	// Messages 对话消息。
	Messages []Message `json:"messages"`
	// System 系统提示词(独立字段便于 provider 组装)。
	System string `json:"system,omitempty"`
	// Tools 可用工具定义。
	Tools []ToolSchema `json:"tools,omitempty"`
	// Temperature 采样温度。
	Temperature float64 `json:"temperature,omitempty"`
	// MaxTokens 最大生成长度。
	MaxTokens int `json:"maxTokens,omitempty"`
}

ChatRequest 是一次模型对话请求。

type ContentBlock

type ContentBlock struct {
	Kind       ContentBlockKind   `json:"kind"`
	Text       string             `json:"text,omitempty"`
	ToolCall   *ToolCall          `json:"toolCall,omitempty"`
	ToolResult *ToolResultContent `json:"toolResult,omitempty"`
	Image      *ImageContent      `json:"image,omitempty"`
}

ContentBlock 是一条消息内的内容块(Derived Union)。

func Image

func Image(img *ImageContent) ContentBlock

Image 构造图片内容块。

func Reasoning

func Reasoning(s string) ContentBlock

Reasoning 构造思维链内容块。

func Text

func Text(s string) ContentBlock

Text 构造文本内容块。

func ToolResult

func ToolResult(tr *ToolResultContent) ContentBlock

ToolResult 构造工具结果内容块。

func ToolUse

func ToolUse(tc *ToolCall) ContentBlock

ToolUse 构造工具调用内容块。

type ContentBlockKind

type ContentBlockKind string

ContentBlockKind 是内容块类型。

const (
	BlockText       ContentBlockKind = "text"
	BlockReasoning  ContentBlockKind = "reasoning"
	BlockToolUse    ContentBlockKind = "tool_use"
	BlockToolResult ContentBlockKind = "tool_result"
	BlockImage      ContentBlockKind = "image"
)

内容块类型枚举。

type ImageContent

type ImageContent struct {
	URL        string `json:"url,omitempty"`
	Attachment string `json:"attachment,omitempty"`
}

ImageContent 是图片内容块(URL 或 Attachment 引用)。

type LLMAdapter

type LLMAdapter interface {
	// Name 返回适配器名(如 "deepseek")。
	Name() string
	// Chat 发起流式对话;每个分片通过 cb 回调,最终返回用量。
	Chat(ctx context.Context, req ChatRequest, cb func(StreamChunk)) (Usage, error)
}

LLMAdapter 是统一的模型调用适配器接口。

type LlmFailure

type LlmFailure struct {
	Kind    LlmFailureKind `json:"kind"`
	Message string         `json:"message"`
	// Cause 携带底层根因(例如 context.DeadlineExceeded / *net.OpError 等),
	// 便于调用方 errors.Is 进行诊断;JSON 序列化时不输出(避免循环引用或敏感信息泄露)。
	// H03 新增:LLM provider 在 ctx 取消 / 网络错误时统一填 Cause,
	// 调用方 errors.Is(f, context.Canceled) 即可区分"用户取消"和"真正网络故障"。
	Cause error `json:"-"`
}

LlmFailure 是携带稳定分类的模型调用失败。

func ClassifyLlmError

func ClassifyLlmError(err error) *LlmFailure

ClassifyLlmError 将任意 error 归类为 LlmFailure;无法归类时返回 unknown。

func NewProviderFailure

func NewProviderFailure(detail string) *LlmFailure

NewProviderFailure 根据 provider detail 构造 *LlmFailure:

  • detail 无法识别 → Kind=unknown;
  • 识别成功 → 对应稳定分类,Message 保留原始 detail 便于诊断。

func (*LlmFailure) Error

func (e *LlmFailure) Error() string

Error 实现 error 接口。

func (*LlmFailure) Unwrap

func (e *LlmFailure) Unwrap() error

Unwrap 支持 errors.Is / errors.As 沿 Cause 链下钻(H03 + Go 1.13+ 错误链)。

type LlmFailureKind

type LlmFailureKind string

LlmFailureKind 是模型失败的稳定分类。

const (
	// FailOverload 服务过载(建议重试)。
	FailOverload LlmFailureKind = "overload"
	// FailRateLimit 速率受限(建议退避重试)。
	FailRateLimit LlmFailureKind = "rate-limit"
	// FailResponseRefusal 模型拒绝响应(不可重试)。
	FailResponseRefusal LlmFailureKind = "response-refusal"
	// FailContextOverflow 上下文超长(需压缩)。
	FailContextOverflow LlmFailureKind = "context-overflow"
	// FailQuota 账户配额/余额耗尽(官方 code QUOTA)。终态,default retry 不重试。
	FailQuota LlmFailureKind = "quota"
	// FailEmptyResponse 响应正常结束但无任何内容块(官方 code EMPTY_RESPONSE)。
	// 退化完成(终态 stop 且 0 输出),不产生助手消息;可安全重试。
	FailEmptyResponse LlmFailureKind = "empty-response"
	// FailInvalidCredential 凭证格式非法(官方 code INVALID_CREDENTIAL)。
	// 区别于"缺失凭证":修复方式为改贮存值而非补值;不在默认可重试集内。
	FailInvalidCredential LlmFailureKind = "invalid-credential"
)

失败分类枚举。

对应官方 packages/llm/llm/src/error.ts 的稳定 HarnessError.code: CONTEXT_WINDOW_EXCEEDED / QUOTA / EMPTY_RESPONSE / INVALID_CREDENTIAL / RATE_LIMIT / (overload) 等。路由一律按 Kind(稳定串),绝不解析 message 文本。

func ClassifyProviderDetail

func ClassifyProviderDetail(detail string) LlmFailureKind

ClassifyProviderDetail 把 provider 提供的错误细节(code/type/message 拼接串,小写化前判别) 映射到稳定 LlmFailureKind;无法识别返回 ""(调用方可归为 unknown)。 语义忠实复刻官方 error.ts 的 isContextWindowExceededError / isQuotaExceededError 判别族。

func (LlmFailureKind) Retryable

func (f LlmFailureKind) Retryable() bool

Retryable 返回该分类是否属于"可重试"(与官方默认 retryable 集对齐):

  • 可重试:overload / rate-limit / context-overflow(压缩后再试)/ empty-response;
  • 不可重试:response-refusal / quota / invalid-credential 及未知。

type Message

type Message struct {
	Role    Role           `json:"role"`
	Content []ContentBlock `json:"content"`
}

Message 是一条对话消息(角色 + 内容块列表)。

func NewAssistantText

func NewAssistantText(text string) Message

NewAssistantText 便捷构造助手文本消息。

func NewUserMessage

func NewUserMessage(text string) Message

NewUserMessage 便捷构造用户文本消息。

type RetryConfig

type RetryConfig struct {
	// MaxAttempts 最大尝试次数(含首次);<=0 时缺省为 3。
	MaxAttempts int
	// BaseBackoff 基础退避时长。
	BaseBackoff time.Duration
	// MaxBackoff 退避上限。
	MaxBackoff time.Duration
	// Jitter 抖动比例(0~1);0 表示不加抖动(便于测试确定性)。
	Jitter float64
}

RetryConfig 是重试参数。

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig 返回默认重试参数。

type RetryMiddleware

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

RetryMiddleware 是带重试的 LLM 适配器装饰器。

func NewRetryMiddleware

func NewRetryMiddleware(inner LLMAdapter, cfg RetryConfig, write RetryWriter) *RetryMiddleware

NewRetryMiddleware 创建重试装饰器。write 可在每次退避后回写 retry 事件。

func (*RetryMiddleware) Chat

func (m *RetryMiddleware) Chat(ctx context.Context, req ChatRequest, cb func(StreamChunk)) (Usage, error)

Chat 执行带重试的流式对话。

func (*RetryMiddleware) Name

func (m *RetryMiddleware) Name() string

Name 透传内部适配器名。

type RetryWriter

type RetryWriter func(data session.LLMRetryData)

RetryWriter 是 llm/retry 事件写出器(典型实现为 session.SessionLog.Append)。

type Role

type Role string

Role 是消息角色。

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

消息角色枚举。

type StreamChunk

type StreamChunk struct {
	Kind      StreamChunkKind `json:"kind"`
	Text      string          `json:"text,omitempty"`
	Reasoning string          `json:"reasoning,omitempty"`
	ToolCall  *ToolCall       `json:"toolCall,omitempty"`
}

StreamChunk 是单次流式回调的分片。

type StreamChunkKind

type StreamChunkKind string

StreamChunkKind 是流式分片类型。

const (
	ChunkText      StreamChunkKind = "text"
	ChunkReasoning StreamChunkKind = "reasoning"
	ChunkToolCall  StreamChunkKind = "tool-call"
	ChunkDone      StreamChunkKind = "done"
)

流式分片类型枚举。

type ToolCall

type ToolCall struct {
	ID    string         `json:"id"`
	Name  string         `json:"name"`
	Input map[string]any `json:"input"`
}

ToolCall 是一次工具调用声明(模型侧)。

type ToolResultContent

type ToolResultContent struct {
	ToolUseID string `json:"toolUseId"`
	Content   string `json:"content"`
	IsError   bool   `json:"isError,omitempty"`
}

ToolResultContent 是一次工具结果内容块。

type ToolSchema

type ToolSchema struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

ToolSchema 是提供给模型的工具定义(OpenAI function 风格)。

type Usage

type Usage struct {
	PromptTokens          int `json:"promptTokens"`
	CompletionTokens      int `json:"completionTokens"`
	PromptCacheHitTokens  int `json:"promptCacheHitTokens,omitempty"`
	PromptCacheMissTokens int `json:"promptCacheMissTokens,omitempty"`
}

Usage 是模型请求的 token 用量(含缓存命中统计,供 N 簇探针使用)。

Directories

Path Synopsis
Package provider_deepseek 实现 DeepSeek 官方 API 的 REST + SSE 流式适配器。
Package provider_deepseek 实现 DeepSeek 官方 API 的 REST + SSE 流式适配器。

Jump to

Keyboard shortcuts

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