Files
ARTEX/third_party/norma/llm/provider.go
T
wangdefa f782b612ec build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到
third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或
改写 tag 都不再影响本仓库构建。

- 已验证 GOPROXY=off 下可完整编译并打出发行包
- go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希)
- 升级方法与授权注意事项见 third_party/README.md
2026-10-20 21:10:41 -07:00

254 lines
9.2 KiB
Go

package llm
import (
"context"
"fmt"
"iter"
"net/http"
"net/url"
"os"
"strings"
"time"
)
// StreamEventType enumerates the normalized streaming events every adapter
// emits, regardless of wire format.
type StreamEventType string
const (
SEMessageStart StreamEventType = "message_start"
SETextDelta StreamEventType = "text_delta"
SEThinkingDelta StreamEventType = "thinking_delta"
SEThinkingSignature StreamEventType = "thinking_signature"
SEToolUseStart StreamEventType = "tool_use_start"
SEToolInputJSON StreamEventType = "tool_input_delta"
SEMessageDelta StreamEventType = "message_delta" // carries stop_reason / usage
SEMessageStop StreamEventType = "message_stop"
)
// StreamEvent is one normalized model-level streaming event (FR-03.5).
type StreamEvent struct {
Type StreamEventType
Text string // text/thinking/tool_input JSON fragment
ToolID string // tool_use_start
ToolName string // tool_use_start
StopReason string // message_delta
Usage Usage // message_start / message_delta
}
// Format selects the wire protocol of a Provider.
type Format string
const (
FormatAnthropic Format = "anthropic"
FormatOpenAI Format = "openai"
// FormatOpenAIResponses speaks the OpenAI Responses API (POST /v1/responses),
// distinct from FormatOpenAI's Chat Completions (/chat/completions).
FormatOpenAIResponses Format = "openai-responses"
)
// MaxTokensFieldCompletion is the Config.MaxTokensField value that moves the
// OpenAI Chat Completions output cap onto "max_completion_tokens". Any other
// value keeps the classic "max_tokens".
const MaxTokensFieldCompletion = "max_completion_tokens"
// Config configures the built-in providers (FR-03.4).
type Config struct {
Format Format
BaseURL string
APIKey string
Model string
APIVersion string // Anthropic only; default 2023-06-01
HTTPClient *http.Client
// Proxy, when set, routes all model requests through the given proxy URL —
// "http://", "https://" or "socks5://" (optionally with user:pass@). It only
// affects the built-in client: when empty, the built-in client falls back to
// the standard HTTP_PROXY / HTTPS_PROXY / NO_PROXY environment variables.
// Ignored when the caller supplies its own HTTPClient.
Proxy string
// MaxRetries bounds transient-failure retries on the model request
// establishment (connection reset / timeout / 429 / 5xx). 0 = default 3;
// negative disables retrying. Only the pre-stream phase is retried (safe);
// a mid-stream drop is surfaced as an error.
MaxRetries int
// RetryInterval, when > 0, replaces the exponential backoff between
// establishment retries with this FIXED wait. 0 (default) keeps the
// 0.5s/1s/2s… ladder capped at 8s. A host that wants a predictable,
// operator-set cadence sets both MaxRetries and this.
RetryInterval time.Duration
// EmptyResponseRetries bounds how many times a completed-but-EMPTY response
// is re-requested (FormatOpenAI only; see emptyResponseRetries). 0 = default
// 2; negative disables. Separate from MaxRetries because an empty-response
// retry re-sends the whole prompt rather than re-establishing a request.
EmptyResponseRetries int
// EmptyResponseInterval, when > 0, replaces the exponential backoff before
// each empty-response retry with this FIXED wait. 0 keeps the ladder.
EmptyResponseInterval time.Duration
// RateLimit, when set, bounds the request rate shared across every caller of
// the built Provider (per-second and/or per-minute). Retries do not count.
RateLimit *RateLimit
// ThinkingType toggles extended/reasoning mode via the request's
// "thinking":{"type":...} field, for both formats. "" omits it (provider
// default); "enabled"/"disabled" are sent verbatim.
ThinkingType string
// ReasoningEffort sets the reasoning strength. "" omits it. For OpenAI it maps
// to "reasoning_effort"; for Anthropic to "output_config":{"effort":...}.
// Typical values: low / medium / high / max.
ReasoningEffort string
// MaxTokensField selects which request key carries the output cap on
// FormatOpenAI (Chat Completions). "" (default) sends the classic
// "max_tokens"; MaxTokensFieldCompletion sends "max_completion_tokens"
// instead. OpenAI's reasoning models reject "max_tokens" outright
// (unsupported_parameter) and accept only the newer key, whose budget covers
// reasoning tokens plus visible output; most OpenAI-compatible gateways still
// take the old one, hence the opt-in default. Exactly one key is ever sent.
// Ignored by the Anthropic and Responses formats, which name the field
// themselves ("max_tokens" / "max_output_tokens").
MaxTokensField string
limiter *rateLimiter // built from RateLimit by NewProvider; shared via the provider
}
// retries returns the effective retry count (0 → default 3; negative → 0).
func (c Config) retries() int {
if c.MaxRetries == 0 {
return 3
}
if c.MaxRetries < 0 {
return 0
}
return c.MaxRetries
}
// retryDelay is the wait before establishment retry number attempt (0-based):
// the configured fixed interval when set, the exponential ladder otherwise.
func (c Config) retryDelay(attempt int) time.Duration {
if c.RetryInterval > 0 {
return c.RetryInterval
}
return expBackoff(attempt)
}
// emptyRetries returns the effective empty-response retry count
// (0 → default emptyResponseRetries; negative → 0).
func (c Config) emptyRetries() int {
if c.EmptyResponseRetries == 0 {
return emptyResponseRetries
}
if c.EmptyResponseRetries < 0 {
return 0
}
return c.EmptyResponseRetries
}
// emptyRetryDelay is the wait before empty-response retry number attempt.
func (c Config) emptyRetryDelay(attempt int) time.Duration {
if c.EmptyResponseInterval > 0 {
return c.EmptyResponseInterval
}
return expBackoff(attempt)
}
// Provider produces a completion, either streamed (Stream) or in a single
// non-streaming round-trip (Complete). Hosts may implement this interface to
// plug in private RPC backends (FR-03.7). Stream's iterator yields normalized
// events; a terminal error is delivered as (zero, err) and ends iteration.
// Complete performs a real non-streaming request (the wire carries
// stream:false and the whole JSON body is parsed at once) and returns the fully
// assembled assistant message, the provider stop reason, and cumulative usage.
type Provider interface {
Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error]
Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error)
}
// NewProvider builds a built-in provider for cfg.Format. Missing APIKey/BaseURL
// fall back to standard environment variables and public endpoints.
func NewProvider(cfg Config) (Provider, error) {
if cfg.HTTPClient == nil {
client, err := defaultHTTPClient(cfg.Proxy)
if err != nil {
return nil, err
}
cfg.HTTPClient = client
}
if cfg.RateLimit != nil {
cfg.limiter = newRateLimiter(*cfg.RateLimit) // shared by the provider (cfg copies the pointer)
}
switch cfg.Format {
case FormatAnthropic:
if cfg.APIKey == "" {
cfg.APIKey = os.Getenv("ANTHROPIC_API_KEY")
}
if cfg.BaseURL == "" {
cfg.BaseURL = envOr("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
}
if cfg.APIVersion == "" {
cfg.APIVersion = "2023-06-01"
}
return &anthropicProvider{cfg: cfg}, nil
case FormatOpenAI:
if cfg.APIKey == "" {
cfg.APIKey = os.Getenv("OPENAI_API_KEY")
}
if cfg.BaseURL == "" {
cfg.BaseURL = envOr("OPENAI_BASE_URL", "https://api.openai.com/v1")
}
return &openaiProvider{cfg: cfg}, nil
case FormatOpenAIResponses:
if cfg.APIKey == "" {
cfg.APIKey = os.Getenv("OPENAI_API_KEY")
}
if cfg.BaseURL == "" {
cfg.BaseURL = envOr("OPENAI_BASE_URL", "https://api.openai.com/v1")
}
return &openaiResponsesProvider{cfg: cfg}, nil
default:
return nil, fmt.Errorf("llm: unknown format %q (use anthropic, openai or openai-responses)", cfg.Format)
}
}
// defaultHTTPClient builds the built-in HTTP client. A non-empty proxy
// ("http://", "https://" or "socks5://") routes every request through it;
// an empty proxy falls back to the standard *_PROXY environment variables
// (net/http's ProxyFromEnvironment). The transport is cloned from
// http.DefaultTransport so it keeps the standard timeouts and connection pool.
func defaultHTTPClient(proxy string) (*http.Client, error) {
tr := http.DefaultTransport.(*http.Transport).Clone()
if proxy == "" {
tr.Proxy = http.ProxyFromEnvironment
return &http.Client{Transport: tr}, nil
}
u, err := url.Parse(proxy)
if err != nil {
return nil, fmt.Errorf("llm: invalid proxy %q: %w", proxy, err)
}
switch u.Scheme {
case "http", "https", "socks5": // supported by net/http's Transport.Proxy
case "":
return nil, fmt.Errorf("llm: proxy %q missing scheme (use http://, https:// or socks5://)", proxy)
default:
return nil, fmt.Errorf("llm: unsupported proxy scheme %q (use http, https or socks5)", u.Scheme)
}
tr.Proxy = http.ProxyURL(u)
return &http.Client{Transport: tr}, nil
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
// joinSystem renders the system segments into a single string.
func joinSystem(segs []string) string {
parts := make([]string, 0, len(segs))
for _, s := range segs {
if s = strings.TrimSpace(s); s != "" {
parts = append(parts, s)
}
}
return strings.Join(parts, "\n\n")
}