agent

package
v0.0.49 Latest Latest
Warning

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

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

README

Agent 公共 API

其他 Backend 模块不需要引用 internal 路径,直接使用 pkg/agent 即可接入 AI。

添加工具

优先使用 Eino 的 InferTool,输入结构会自动生成工具参数 schema:

type SearchRequest struct {
	Keyword string `json:"keyword" jsonschema_description:"搜索关键词"`
}

searchTool, err := agent.InferTool[SearchRequest, string](
	"search_records",
	"搜索业务记录",
	func(ctx context.Context, request SearchRequest) (string, error) {
		return searchRecords(ctx, request.Keyword)
	},
)
if err != nil {
	return err
}

创建 Runtime 时传入工具,或在运行时追加:

client := agent.NewResponsesClient(modelConfig)
runtime := agent.NewRuntime(agent.RuntimeConfig{
	Client:     client,
	AdminTools: []agent.Tool{searchTool},
})
runtime.RegisterTool("admin", anotherTool)

不接入权限系统时 Checker 保持 nil;需要按终端控制工具时实现 agent.ToolAccessChecker

结构化输出

评论审核、内容提取等业务可以复用公共聊天客户端和结构化运行器,不需要引用 internal/biz/agent

client := agent.NewChatClient(modelConfig)
runner := agent.NewStructuredRunner(client)
schema, err := agent.SchemaFor[ReviewResult]()
if err != nil {
	return err
}
err = runner.Generate(ctx, instruction, []*agent.Part{
	agent.TextPart(content),
	agent.ImageURLPart(imageURL),
}, schema, &result)

Documentation

Index

Constants

View Source
const (
	// RoleUser 表示用户消息角色。
	RoleUser = "user"
	// RoleAI 表示助手消息角色。
	RoleAI = "ai"

	// KindText 表示普通文本消息类型。
	KindText = "text"
)

Variables

This section is empty.

Functions

func DecodeContent added in v0.0.28

func DecodeContent(content string, out any) error

DecodeContent 解码模型返回的结构化 JSON 文本。

func SchemaPrompt added in v0.0.28

func SchemaPrompt(outputSchema *Schema) string

SchemaPrompt 构造结构化输出的 JSON Schema 文本约束。

Types

type Attachment

type Attachment struct {
	// Name 附件名称,用于提示词中展示给模型。
	Name string `json:"name"`
	// Size 附件大小,模型无法直接读取文件时会作为辅助说明。
	Size int64 `json:"size"`
	// URL 附件地址,用于追踪来源;不会直接作为远端图片地址传给模型。
	URL string `json:"url"`
	// MIMEType 附件 MIME 类型,决定文本提取和图片输入路径。
	MIMEType string `json:"mimeType"`
	// Content 附件文本内容,通常来自文本、JSON、XML、CSV 等可直接读取的文件。
	Content string `json:"content"`
	// Bytes 附件原始字节,图片类附件会通过该字段作为视觉输入传给模型。
	Bytes []byte `json:"-"`
}

Attachment 表示 AI 助手运行时可消费的附件。

前端上传后传入的 proto 附件只包含文件元信息;业务层会读取 OSS 文件内容后填充 Content 或 Bytes。运行时根据 MIME 类型决定将附件作为文本片段还是多模态图片输入。

type ChatClient added in v0.0.28

type ChatClient = model.ChatClient

ChatClient 是结构化任务使用的聊天模型客户端。

func NewChatClient added in v0.0.28

func NewChatClient(modelConfig *configv1.AI_Model) *ChatClient

NewChatClient 根据 Backend AI 模型配置创建聊天模型客户端。

type Message

type Message struct {
	// Role 消息角色,只允许 user 或 ai。
	Role string `json:"role"`
	// Content 消息正文,进入模型前会再次过滤空白内容。
	Content string `json:"content"`
	// Tools 当前历史轮次实际使用过的工具,仅用于短追问时延续候选工具。
	Tools []ToolUsage `json:"tools"`
}

Message 表示写入 AI 助手上下文的历史消息。

该结构只保留模型构造上下文所需的最小信息,调用方从数据库消息或其他来源转换时, 不需要把附件、模型、降级等展示层元数据带入历史上下文。

type Part added in v0.0.28

type Part = structured.Part

Part 是结构化任务可传给模型的多模态输入片段。

func ImageDataPart added in v0.0.28

func ImageDataPart(data []byte, mimeType string) *Part

ImageDataPart 构造图片字节输入片段。

func ImageURLPart added in v0.0.28

func ImageURLPart(rawURL string) *Part

ImageURLPart 构造远程图片输入片段。

func TextPart added in v0.0.28

func TextPart(content string) *Part

TextPart 构造文本输入片段。

type Response

type Response struct {
	// Content 回复正文,面向前端展示。
	Content string `json:"content"`
	// Token 本次调用 token 消耗。
	Token TokenUsage `json:"token"`
	// Tools 本轮回复实际使用的工具列表。
	Tools []ToolUsage `json:"tools"`
	// Source 回复来源,例如 llm 或 fallback。
	Source string `json:"source"`
	// Model 使用的模型名称,便于前端展示和排障。
	Model string `json:"model"`
	// Fallback 标记本次回复是否由本地兜底逻辑生成。
	Fallback bool `json:"fallback"`
	// FallbackReason 记录触发降级的底层错误信息,仅用于排障和后台展示。
	FallbackReason string `json:"fallbackReason"`
	// Flow 记录本次回复所属的模块固定流程。
	Flow string `json:"flow"`
	// Step 记录本次回复所属的流程步骤。
	Step string `json:"step"`
	// BlocksJSON 记录模块定义的结构化内容 JSON。
	BlocksJSON string `json:"blocksJson"`
}

Response 表示 AI 助手单轮回复结果。

该结构同时承载模型原始回复与本地降级回复。落库时会被序列化为包含正文和元信息的 JSON,返回前端时再拆回正文、来源、模型名称和降级原因。

type ResponsesClient

type ResponsesClient = model.ResponsesClient

ResponsesClient 是 Responses API 模型客户端。

func NewResponsesClient

func NewResponsesClient(modelConfig *configv1.AI_Model) *ResponsesClient

NewResponsesClient 根据 Backend AI 模型配置创建 Responses 客户端。

type Runtime

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

Runtime 封装流式 AI 助手运行时。

Runtime 只负责把业务层准备好的输入组装为 Eino 消息并交给模型执行,不直接处理数据库、 OSS、鉴权或前端协议。这样 AI 助手链路可以把“业务准备”和“模型运行”分开维护。

func NewRuntime

func NewRuntime(config RuntimeConfig) *Runtime

NewRuntime 创建可被外部模块复用的 AI Runtime。

func NewRuntimeWithTools

func NewRuntimeWithTools(client *ResponsesClient, tools ...Tool) *Runtime

NewRuntimeWithTools 创建只使用管理端工具集合的 Runtime。

func (*Runtime) Enabled

func (r *Runtime) Enabled() bool

Enabled 判断 AI 助手运行时是否可用。

func (*Runtime) EnabledToolNames

func (r *Runtime) EnabledToolNames(ctx context.Context, terminal string) map[string]bool

EnabledToolNames 返回当前终端实际启用的 Agent 工具名集合。

func (*Runtime) InvokeTool

func (r *Runtime) InvokeTool(ctx context.Context, terminal string, name string, arguments string) (*ToolInvokeResult, error)

InvokeTool 按工具名直接调用当前终端已启用的 Agent 工具。

func (*Runtime) Model

func (r *Runtime) Model() string

Model 返回 AI 助手当前使用的模型名称。

func (*Runtime) RegisterTool

func (r *Runtime) RegisterTool(terminal string, value Tool) error

RegisterTool 将一个工具追加到指定终端;重复名称按首次注册的工具执行。

func (*Runtime) RegisterTools

func (r *Runtime) RegisterTools(terminal string, values ...Tool) error

RegisterTools 将工具追加到指定终端,支持运行时扩展工具集合。

func (*Runtime) Run

func (r *Runtime) Run(ctx context.Context, input RuntimeInput) (*Response, error)

Run 使用生成式模式运行助手。

该方法用于普通 RPC 或非流式调用:先构建带历史上下文的 Eino 消息列表, 再等待模型完整回复。

func (*Runtime) RunStream

func (r *Runtime) RunStream(ctx context.Context, input RuntimeInput, onDelta func(string)) (*Response, error)

RunStream 使用流式模式运行助手。

该方法用于管理端 direct SSE:模型返回文本片段时会透传给 onDelta, 最终仍返回完整回复供业务层落库。

type RuntimeConfig

type RuntimeConfig struct {
	// Client 是 Responses API 模型客户端。
	Client *ResponsesClient
	// Checker 是可选的工具权限检查器;为 nil 时全部注册工具默认启用。
	Checker ToolAccessChecker
	// AdminTools 是管理端工具集合。
	AdminTools []Tool
	// AppTools 是应用端工具集合。
	AppTools []Tool
}

RuntimeConfig 是公开 Runtime 的初始化配置。

type RuntimeInput

type RuntimeInput struct {
	// Terminal 终端标识,例如 admin 或 app,会注入到系统提示词。
	Terminal string
	// UserName 当前用户展示名称,会注入到系统提示词供模型理解上下文。
	UserName string
	// SessionTitle 当前会话标题,会注入到系统提示词供模型理解会话语境。
	SessionTitle string
	// SessionID 当前会话编号,预留给后续追踪、工具调用或日志串联。
	SessionID string
	// Summary 当前会话摘要,会注入到系统提示词作为压缩后的长期上下文。
	Summary string
	// Content 本轮用户文本内容。
	Content string
	// Attachments 本轮用户附件列表,已经由业务层读取过可用内容。
	Attachments []Attachment
	// History 会话历史消息,按时间正序传入。
	History []Message
}

RuntimeInput 表示 AI 助手运行时输入。

业务层在进入 Runtime 前完成鉴权、会话归属、附件读取、历史消息查询等工作; Runtime 只负责将这些输入组装成 Eino 消息和当前轮用户消息。

type Schema added in v0.0.28

type Schema = structured.Schema

Schema 是结构化输出使用的 JSON Schema。

func SchemaFor added in v0.0.28

func SchemaFor[T any]() (*Schema, error)

SchemaFor 根据结果类型生成 JSON Schema。

type StructuredRunner added in v0.0.28

type StructuredRunner = structured.Runner

StructuredRunner 是按 JSON Schema 生成并解析模型结果的运行器。

func NewStructuredRunner added in v0.0.28

func NewStructuredRunner(client *ChatClient) *StructuredRunner

NewStructuredRunner 创建结构化输出运行器。

type TokenUsage

type TokenUsage struct {
	// Input 输入 token 数。
	Input int32 `json:"input"`
	// Output 输出 token 数。
	Output int32 `json:"output"`
	// Cache 命中缓存 token 数。
	Cache int32 `json:"cache"`
	// Total 总 token 数。
	Total int32 `json:"total"`
}

TokenUsage 表示 AI 助手单轮真实 token 使用量。

type Tool

type Tool = tool.InvokableTool

Tool 是 Eino 可执行工具接口。

func InferTool

func InferTool[T, D any](name string, description string, fn utils.InvokeFunc[T, D], options ...utils.Option) (Tool, error)

InferTool 根据输入结构自动生成 Eino 工具 schema 和执行器。

type ToolAccessChecker

type ToolAccessChecker interface {
	// ToolConfigs 返回当前终端允许暴露给 Agent 的工具配置。
	ToolConfigs(ctx context.Context, terminal string, names []string) (map[string]ToolConfig, error)
}

ToolAccessChecker 判断 Agent 工具是否允许在当前终端暴露。

type ToolConfig

type ToolConfig struct {
	// Enabled 表示工具是否允许暴露给 Agent。
	Enabled bool
	// Prompts 表示覆盖生成工具描述和命中判断的业务提示词。
	Prompts []string
}

ToolConfig 表示 Agent 工具运行时配置。

type ToolInvokeResult

type ToolInvokeResult struct {
	// Output 工具原始输出 JSON。
	Output string
	// Usage 本次工具调用的后台展示记录。
	Usage ToolUsage
}

ToolInvokeResult 表示直接调用 Agent 工具后的结果。

type ToolUsage

type ToolUsage struct {
	// Type 工具类型,例如 function 或 server。
	Type string `json:"type"`
	// Name 工具名称,用于排障和唯一识别。
	Name string `json:"name"`
	// Title 工具展示名称,优先使用生成工具描述。
	Title string `json:"title"`
	// Status 工具状态,例如 success、error。
	Status string `json:"status"`
	// Input 工具原始入参 JSON,用于后台展开排障。
	Input string `json:"input"`
	// Output 工具原始出参 JSON,用于后台展开排障。
	Output string `json:"output"`
}

ToolUsage 表示 AI 助手单轮回复涉及的工具。

Jump to

Keyboard shortcuts

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