Help us shape the future of Go! Take the 2026 Go Developer Survey

llm

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package llm 提供对大模型 OpenAI 兼容协议的薄封装(基于 Eino ChatModel)。 该包为纯客户端层,不依赖 engine / service,供 service/ai.go 统一编排调用。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ActionPrompt

func ActionPrompt(lang, action, detail string) string

ActionPrompt 生成任务级用户消息(任务指令固定,不交给用户改 system prompt)。

func AgentRules

func AgentRules(lang, target string) string

AgentRules 返回 agent 模式的工具使用规则段(含目标库工作范围,按语言)。 该段始终追加在 system prompt 末尾,保证 agent 工具调用规则不被自定义 prompt 覆盖。

func AgentRulesFor

func AgentRulesFor(lang, target string, pgSchema bool) string

AgentRulesFor 同 AgentRules;pgSchema=true(PG 系连接)时追加 schema 限定名规则: 表引用必须 schema.table,禁止 database.table 的 MySQL 风格。

func BuildSchemaText

func BuildSchemaText(lang string, tables []TableInfo, maxTables, maxChars int) string

BuildSchemaText 将表结构渲染为注入文本: - 表/列名统一用反引号包裹(内嵌反引号双写转义),防间接 Prompt 注入; - 排除敏感列(PII 脱敏); - maxTables 控制最多注入的表数量(<=0 表示不限),超出部分省略; - maxChars 控制注入文本的字符上限(<=0 表示不裁剪),超出部分裁剪。 两个上限由调用方从配置(ai.max_schema_tables / ai.max_schema_chars)传入。

func BuildSchemaTextFull

func BuildSchemaTextFull(lang string, tables []TableInfo, maxTables, maxChars int) string

BuildSchemaTextFull 与 BuildSchemaText 相同,但不做敏感列(PII)过滤,返回完整表结构。 供 get_schema 等「模型主动按需查询真实表结构」的工具使用: 过滤会破坏结构完整性,导致模型误判字段不存在(如 email/mobile/password_* 等)。

func ExtractSQL

func ExtractSQL(s string) string

ExtractSQL 从模型输出中提取 SQL: - 优先提取标准 ```sql ... ``` 代码围栏块(可嵌在解释文字中间); - 无围栏时兼容旧格式:剥离首尾 ```,整段作为 SQL; - 剥离行注释(--)与块注释(/* */)(先剥离再交由 checkDangerous,防注释绕过); - 收尾清理。

func KnownTables

func KnownTables(lang, target string, names []string) string

KnownTables 渲染「已知表名录」段(目标库 + 表名列表,按语言)。 表名超上限时省略并提示用工具查询剩余。

func NormLang

func NormLang(lang string) string

NormLang 语言代码归一:zh 前缀→zh、en 前缀→en、未知→zh(与业务注册表一致,可扩展)。

func RenderSystemPrompt

func RenderSystemPrompt(lang, custom, dialect, schema string) string

RenderSystemPrompt 渲染最终 system prompt: - 使用用户自定义模板(custom),为空则用内置默认模板(按 lang 选择); - 替换 {dialect}; - {schema} 占位符仅控制注入位置;模板缺失 {schema} 时在末尾追加 schema 段,保证上下文不丢。

Types

type AgentCallbacks

type AgentCallbacks struct {
	// OnContent 文本增量(等同普通流式的 onDelta)。
	// 工具调用事件由 service 层经工具函数内的 ToolSink 透传,不在这里处理。
	OnContent func(delta string)
}

AgentCallbacks agent 执行期间的对外回调(SSE 工具事件 / 文本增量)。

type Client

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

Client 封装单个 Eino ChatModel 实例(每个配置可复用一个客户端)。

func NewClient

func NewClient(ctx context.Context, cfg Config) (*Client, error)

NewClient 创建 LLM 客户端。ctx 仅用于初始化,不参与后续调用。

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, msgs []*schema.Message) (string, Usage, error)

Chat 非流式生成,返回完整文本与 usage。

func (*Client) ChatStream

func (c *Client) ChatStream(ctx context.Context, msgs []*schema.Message, onDelta func(string)) (Usage, error)

ChatStream 流式生成:每收到一段增量回调 onDelta,结束后返回流尾 usage(模型未提供则记 0)。 客户端断开 ctx 即可终止上游调用。

type ColumnInfo

type ColumnInfo struct {
	Name     string
	Type     string
	Nullable bool
	Comment  string
}

ColumnInfo 列信息。

type Config

type Config struct {
	BaseURL     string
	APIKey      string
	Model       string
	Temperature float32
	MaxTokens   int
	Timeout     time.Duration
}

Config 为创建 LLM 客户端所需的配置(来自 AppConfig.AI,已由 service 层取值)。

type ReactAgent

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

ReactAgent 封装 Eino react.Agent:会话级复用(每次 Stream 传入完整历史)。 注意:内部持有独立 ChatModel 实例(react 会对其 BindTools 切换绑定), 不可与全局共享的 aiClient 混用,避免多会话工具绑定相互覆盖。

func NewReactAgent

func NewReactAgent(ctx context.Context, cfg Config, tools []tool.InvokableTool, systemPrompt string) (*ReactAgent, error)

NewReactAgent 创建 React Agent。 systemPrompt 由 MessageModifier 注入:若 msgs 已含 system 消息则不重复注入(幂等)。

func (*ReactAgent) Stream

func (a *ReactAgent) Stream(ctx context.Context, msgs []*schema.Message, cb AgentCallbacks) (string, Usage, error)

Stream 执行一轮 agent 对话(msgs 需以用户消息结尾,可含 system)。 参照 Eino 官方 react demo 的简洁写法:直接消费 agent.Stream 返回的最终输出流, 工具调用的中间过程由框架内部自动处理,外部不主动 drain(避免扇出背压死锁)。

返回:最终回复内容、本轮累计 usage(模型末轮 usage,工具轮次的 usage 框架不直接透出)、 以及最终答案消息(供会话持久化)。

type TableInfo

type TableInfo struct {
	Schema  string       // 库名(可为空)
	Table   string       // 表名
	Comment string       // 表注释(可为空)
	Columns []ColumnInfo // 列信息(渲染时可按需过滤敏感列,见 BuildSchemaTextFull)
}

TableInfo 表结构信息(service 层从 engine 元数据转换而来,本包不依赖 engine)。

type ToolTexts

type ToolTexts struct {
	ListDBsDesc         string // list_databases 工具描述
	ListTablesDesc      string // list_tables 工具描述
	GetSchemaDesc       string // get_schema 工具描述
	DBNotFound          string // 库不存在提示(list_tables,%q=库名 %s=可用库列表)
	DBNotFoundSchema    string // 库不存在提示(get_schema,同上)
	TableNotFound       string // 表不存在提示(%q=表名 %q=库名 %s=可用表列表)
	ErrListDBs          string // 列出数据库失败错误(%w=原始错误)
	ErrListTables       string // 列出表失败错误(%w=原始错误)
	ErrListDBsForSchema string // get_schema 前置获取库列表失败错误(%w=原始错误)
}

ToolTexts agent 只读工具(list_databases/list_tables/get_schema)的描述与输出文本, 模型可见,需与会话语言一致(缺失语言回退 zh)。

func ToolTextsFor

func ToolTextsFor(lang string) ToolTexts

ToolTextsFor 按语言取 agent 工具文本,缺失语言回退 zh。

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage 记录单轮/会话累计的 token 消耗(透出模型返回的 usage,不自数)。

func (*Usage) Add

func (u *Usage) Add(o Usage)

Add 累加一轮消耗到累计值。

func (Usage) IsZero

func (u Usage) IsZero() bool

IsZero 判断 usage 是否为空(模型未返回时记 0)。

Jump to

Keyboard shortcuts

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