llm

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrProviderNotRegistered = errors.New("llm provider not registered")

ErrProviderNotRegistered 当 provider 未被注册时返回。

View Source
var ErrStreamNotSupported = errors.New("streaming not supported")

ErrStreamNotSupported 当 provider 不支持流式时返回。

Functions

func FloatPtr

func FloatPtr(v float64) *float64

FloatPtr 工具函数,便于在配置中声明浮点指针。

func IntPtr

func IntPtr(v int) *int

IntPtr 工具函数,便于在配置中声明整型指针。

func RegisterEinoAgentProvider

func RegisterEinoAgentProvider(provider Provider, constructor func(cfg Config) (EinoAgent, error))

RegisterEinoAgentProvider 将 Eino Agent/Flow 扩展适配为统一接口。

func RegisterEinoProvider

func RegisterEinoProvider(provider Provider, constructor func(cfg Config) (EinoExecutor, error))

RegisterEinoProvider 帮助方法:接受 eino executor,并封装为 Adapter。

func RegisterProvider

func RegisterProvider(provider Provider, builder Builder)

RegisterProvider 注册新的 provider 构造器。

Types

type Adapter

type Adapter interface {
	Chat(ctx context.Context, req ChatRequest) (*ChatCompletion, error)
}

Adapter 定义统一的推理接口。

type AgentOrchestrator

type AgentOrchestrator struct {
	Client        *Client
	Tools         map[string]ToolExecutor
	MaxIterations int
}

AgentOrchestrator 简易 Agent 编排器: 1. 调用模型获取 tool_calls。 2. 顺序执行工具,并将结果(含错误信息)写回上下文。 3. 将工具输出追加到对话,再次发送给模型,直到没有 tool_calls 或达到迭代上限。

func (*AgentOrchestrator) Run

func (a *AgentOrchestrator) Run(ctx context.Context, messages []Message, opts ...Option) (*ChatCompletion, error)

Run 执行带工具的对话流程。

type Builder

type Builder func(ctx context.Context, cfg Config) (Adapter, error)

Builder 构造具体 provider 的 Adapter。

type ChatCompletion

type ChatCompletion struct {
	ID       string             `json:"id"`
	Model    string             `json:"model"`
	Provider Provider           `json:"provider"`
	Created  time.Time          `json:"created"`
	Choices  []CompletionChoice `json:"choices"`
	Usage    CompletionUsage    `json:"usage"`
	Raw      interface{}        `json:"raw,omitempty"`
}

ChatCompletion 标准化的回复结构。

type ChatRequest

type ChatRequest struct {
	Messages []Message
	Options  RequestOptions
}

ChatRequest 内部标准化的请求。

type ChatStreamChunk

type ChatStreamChunk struct {
	Index        int
	Delta        string
	FinishReason string
	Raw          interface{}
}

ChatStreamChunk 流式返回片段。

type Client

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

Client 对外暴露的统一入口。

func NewClient

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

NewClient 根据配置创建通用 LLM Client。

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, messages []Message, opts ...Option) (*ChatCompletion, error)

Chat 统一的非流式接口。

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, messages []Message, opts ...Option) (<-chan ChatStreamChunk, func(), error)

Stream 尝试流式调用,若 provider 未实现则返回 ErrStreamNotSupported。

type CompletionChoice

type CompletionChoice struct {
	Index        int         `json:"index"`
	Message      Message     `json:"message"`
	FinishReason string      `json:"finish_reason"`
	ProviderMeta interface{} `json:"provider_meta,omitempty"`
}

CompletionChoice 单次回复的选择。

type CompletionUsage

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

CompletionUsage 记录 tokens 用量。

type Config

type Config struct {
	Provider Provider          `json:"provider" yaml:"provider" mapstructure:"provider"`
	Model    string            `json:"model" yaml:"model" mapstructure:"model"`
	BaseURL  string            `json:"base_url,omitempty" yaml:"base_url,omitempty" mapstructure:"base_url"`
	APIKey   string            `json:"api_key,omitempty" yaml:"api_key,omitempty" mapstructure:"api_key"`
	Version  string            `json:"version,omitempty" yaml:"version,omitempty" mapstructure:"version"`
	Timeout  time.Duration     `json:"timeout,omitempty" yaml:"timeout,omitempty" mapstructure:"timeout"`
	Options  RequestOptions    `json:"options,omitempty" yaml:"options,omitempty" mapstructure:"options"`
	Headers  map[string]string `json:"headers,omitempty" yaml:"headers,omitempty" mapstructure:"headers"`
}

Config 定义一个模型的基础配置,可从配置文件直接映射。

func (Config) RequestFromMessages

func (c Config) RequestFromMessages(messages []Message, opts ...Option) ChatRequest

RequestFromMessages 构建请求体。

type EinoAgent

type EinoAgent interface {
	Run(ctx context.Context, messages []Message, options RequestOptions) (*ChatCompletion, error)
}

EinoAgent 兼容 Eino Agent/编排接口。

type EinoExecutor

type EinoExecutor interface {
	Chat(ctx context.Context, messages []Message, options RequestOptions) (*ChatCompletion, error)
}

EinoExecutor 抽象出 eino 风格的执行器,方便用户在外部直接使用官方实现。 该接口只要求一个 Chat 方法,与官方 schema 解耦,避免在无法联网时阻塞编译。

type Message

type Message struct {
	Role       MessageRole `json:"role" yaml:"role"`
	Content    string      `json:"content" yaml:"content"`
	Name       string      `json:"name,omitempty" yaml:"name,omitempty"`
	ToolCalls  []ToolCall  `json:"tool_calls,omitempty" yaml:"tool_calls,omitempty"`
	ToolCallID string      `json:"tool_call_id,omitempty" yaml:"tool_call_id,omitempty"`
}

Message 聊天消息定义,兼容主流 Chat Completions 协议。

type MessageRole

type MessageRole string

MessageRole 统一的消息角色定义。

const (
	RoleSystem    MessageRole = "system"
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
	RoleTool      MessageRole = "tool"
)

type Option

type Option func(*RequestOptions)

Option 函数式可选项。

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders 附加请求头(与默认合并)。

func WithMaxTokens

func WithMaxTokens(value int) Option

WithMaxTokens 覆盖最大 tokens。

func WithProviderRaw

func WithProviderRaw(values map[string]any) Option

WithProviderRaw 透传给具体 provider 的参数。

func WithStop

func WithStop(stop ...string) Option

WithStop 覆盖停止词。

func WithStream

func WithStream(stream bool) Option

WithStream 开启或关闭流式。

func WithTemperature

func WithTemperature(value float64) Option

WithTemperature 覆盖采样温度。

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout 覆盖单次请求超时。

func WithToolChoice

func WithToolChoice(choice string) Option

WithToolChoice 指定工具调用策略(auto/none/required/具体工具名)。

func WithTools

func WithTools(tools []ToolDefinition) Option

WithTools 设置可用工具列表。

func WithTopP

func WithTopP(value float64) Option

WithTopP 覆盖 top_p。

func WithUser

func WithUser(user string) Option

WithUser 传递 user 字段。

type Provider

type Provider string

Provider 代表内置或自定义的大模型供应商。

const (
	// ProviderOpenAI 使用 OpenAI Chat Completions 协议。
	ProviderOpenAI Provider = "openai"
	// ProviderEinoAgent 预留给 Eino Agent 端到端编排(自定义注册时使用)。
	ProviderEinoAgent Provider = "eino-agent"
)

type RequestOptions

type RequestOptions struct {
	Temperature *float64          `json:"temperature,omitempty" yaml:"temperature,omitempty"`
	TopP        *float64          `json:"top_p,omitempty" yaml:"top_p,omitempty"`
	MaxTokens   *int              `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
	Stop        []string          `json:"stop,omitempty" yaml:"stop,omitempty"`
	User        string            `json:"user,omitempty" yaml:"user,omitempty"`
	Stream      bool              `json:"stream,omitempty" yaml:"stream,omitempty"`
	Metadata    map[string]any    `json:"metadata,omitempty" yaml:"metadata,omitempty"`
	Timeout     time.Duration     `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	Headers     map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
	ProviderRaw map[string]any    `json:"provider_raw,omitempty" yaml:"provider_raw,omitempty"`
	Tools       []ToolDefinition  `json:"tools,omitempty" yaml:"tools,omitempty"`
	ToolChoice  string            `json:"tool_choice,omitempty" yaml:"tool_choice,omitempty"` // auto/none/required/具体工具名(OpenAI 风格)
}

RequestOptions 运行时请求参数(可覆盖默认配置)。

type StreamingAdapter

type StreamingAdapter interface {
	Stream(ctx context.Context, req ChatRequest) (<-chan ChatStreamChunk, func(), error)
}

StreamingAdapter 定义可选的流式接口。

type ToolCall

type ToolCall struct {
	ID       string           `json:"id" yaml:"id"`
	Type     string           `json:"type" yaml:"type"` // 目前使用 "function"
	Function ToolFunctionCall `json:"function" yaml:"function"`
}

ToolCall 表示一次工具调用(assistant 侧),或工具响应(tool 侧)。

type ToolDefinition

type ToolDefinition struct {
	Name        string                 `json:"name" yaml:"name"`
	Description string                 `json:"description,omitempty" yaml:"description,omitempty"`
	Parameters  map[string]any         `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	Meta        map[string]interface{} `json:"meta,omitempty" yaml:"meta,omitempty"`
}

ToolDefinition 用于向模型暴露可用工具。

type ToolExecutor

type ToolExecutor func(ctx context.Context, call ToolCall) (string, error)

ToolExecutor 统一的工具执行接口。

type ToolFunctionCall

type ToolFunctionCall struct {
	Name      string `json:"name" yaml:"name"`
	Arguments string `json:"arguments" yaml:"arguments"` // 原始 JSON 字符串
}

ToolFunctionCall 代表一次函数调用。

type Validator

type Validator interface {
	Validate() error
}

Validator 校验请求输入。

Jump to

Keyboard shortcuts

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