按 DevDocs/design/01 §2.1/§2.2 与 design/04 §3.2 实现(规格含联网核过的官方依据:思考内容刻意不角色化、不写分步思考指令、思考控制只走参数级)。
- 人格 schema 新增 thinking:budgetTokens / effort / showToUser(*bool,省略=nil=保持现行为,显式 false=只落库) / mode(default|on|off→Enable 三态);非法 mode/负预算 → ErrInvalidThinking(不静默)
- 5 个死字段接上注入:personality→values→speechStyle→catchphrase→background 拼为独立段落(带【】小标题,空值不拼);**全空时输出与旧实现逐字节一致**(有专门测试)
- model.Request 新增 Thinking{ BudgetTokens, Enable } 与 ReasoningEffort;新增 model/reasoning.go:厂商识别(模型名→baseURL 兜底)、取值白名单(OpenAI 系 none…max / DeepSeek low|high|max)、非法值降级+WARN、**不支持一律 WARN 而非静默**;Anthropic 映射 thinking{budget_tokens} 并**保证 budget<max_tokens**(不足时抬高 max_tokens+WARN,正是历史上思考吃光预算→空回复那个坑)
- loop:新增 Options.ThinkingShowToUser(*bool) 仅门控 thinking_* 帧(正文/工具帧不受影响);场景级 mute 语义不变
- 补一处任务清单外但必需的接线:persona→model.Request 的 thinking 映射(否则 budget/effort/mode 会变成新的死字段);showToUser 刻意不产生 Thinking(纯呈现开关)
- 管理端:personaUpsertRequest 补 thinking DTO + 校验(400);PUT 省略时**保留已存块**(防旧客户端抹配置);写侧 yaml round-trip 已验证
- Docs/api-client v0.40→v0.41(可选请求字段)
- 测试:26 个新用例(loader 解析/拼接逐字节/映射、anthropic 非流式+流式预算约束、openai 透传/降级/丢弃、Qwen 诚实 WARN、loop 门控、DTO round-trip);3 次变异验证(省略与 false 混同 / 去掉预算约束 / 短路门控 各自 FAIL)
- 验收:go build/vet/test 全绿(含 57 包)+ linux/darwin 交叉编译 + 前端 build;唯一 FAIL 是既有 flake TestInterruptCancelsTurnAndClearsPending(3/20 新代码 vs 3/20 纯 HEAD,已归因非本次引入)
234 lines
6.8 KiB
Go
234 lines
6.8 KiB
Go
package model
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/config"
|
|
)
|
|
|
|
// Wire constraints for the OpenAI-compatible /chat/completions protocol.
|
|
const (
|
|
// sseDataPrefix marks an SSE event line carrying a JSON payload.
|
|
sseDataPrefix = "data: "
|
|
// sseDone is the terminal SSE sentinel.
|
|
sseDone = "[DONE]"
|
|
// sseBufInit is the initial bufio.Scanner read buffer size.
|
|
sseBufInit = 64 * 1024
|
|
// maxSSELineBytes caps a single SSE event line.
|
|
maxSSELineBytes = 1024 * 1024
|
|
// errBodyCap bounds how much of an error body is read for the message.
|
|
errBodyCap = 512
|
|
// defaultHTTPTimeout bounds a single provider call when Options.Timeout is 0.
|
|
defaultHTTPTimeout = 180 * time.Second
|
|
)
|
|
|
|
// OpenAIChatAdapter calls an OpenAI-compatible /chat/completions endpoint. It is
|
|
// constructed from a config.LLMConfig and implements Adapter for both
|
|
// non-streaming and token-level SSE streaming.
|
|
type OpenAIChatAdapter struct {
|
|
name string
|
|
baseURL string
|
|
apiKey string
|
|
model string
|
|
client *http.Client
|
|
recorder Recorder
|
|
// log reports reasoning_effort validation and ignored thinking directives. It
|
|
// is never nil: a discard logger tagged with this adapter's source is
|
|
// installed when the caller supplies none, so a decision is always traceable.
|
|
log *slog.Logger
|
|
}
|
|
|
|
// OpenAIOption configures an OpenAIChatAdapter.
|
|
type OpenAIOption func(*OpenAIChatAdapter)
|
|
|
|
// WithHTTPClient overrides the default HTTP client (used to inject mocks or a
|
|
// tuned transport in tests and production).
|
|
func WithHTTPClient(c *http.Client) OpenAIOption {
|
|
return func(a *OpenAIChatAdapter) { a.client = c }
|
|
}
|
|
|
|
// WithRecorder wires a per-call Recorder for CallRecord accounting.
|
|
func WithRecorder(r Recorder) OpenAIOption {
|
|
return func(a *OpenAIChatAdapter) { a.recorder = r }
|
|
}
|
|
|
|
// WithModel overrides the adapter's default model name.
|
|
func WithModel(m string) OpenAIOption {
|
|
return func(a *OpenAIChatAdapter) { a.model = m }
|
|
}
|
|
|
|
// WithOpenAILogger attaches the logger used to report reasoning_effort
|
|
// validation and ignored thinking directives. A nil logger is ignored so the
|
|
// discard default stays in place.
|
|
func WithOpenAILogger(l *slog.Logger) OpenAIOption {
|
|
return func(a *OpenAIChatAdapter) {
|
|
if l != nil {
|
|
a.log = l
|
|
}
|
|
}
|
|
}
|
|
|
|
// NewOpenAIChat builds an adapter from a supplier config. baseURL is trimmed of
|
|
// any trailing slash before the /chat/completions path is appended.
|
|
func NewOpenAIChat(cfg config.LLMConfig, opts ...OpenAIOption) *OpenAIChatAdapter {
|
|
a := &OpenAIChatAdapter{
|
|
name: "openai",
|
|
baseURL: strings.TrimRight(cfg.BaseURL, "/"),
|
|
apiKey: cfg.APIKey,
|
|
model: cfg.Model,
|
|
client: &http.Client{
|
|
Transport: http.DefaultTransport,
|
|
Timeout: defaultHTTPTimeout,
|
|
},
|
|
log: discardLogger("runtime/model/openai"),
|
|
}
|
|
for _, o := range opts {
|
|
o(a)
|
|
}
|
|
return a
|
|
}
|
|
|
|
// Name returns the adapter identifier.
|
|
func (a *OpenAIChatAdapter) Name() string { return a.name }
|
|
|
|
// Chat performs a non-streaming completion.
|
|
func (a *OpenAIChatAdapter) Chat(ctx context.Context, req Request, opts Options) (Response, error) {
|
|
start := time.Now()
|
|
if a.baseURL == "" {
|
|
return Response{}, ErrUpstream
|
|
}
|
|
ctx, cancel := withCallTimeout(ctx, opts)
|
|
defer cancel()
|
|
model, err := a.resolveModel(req)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
req.Model = model
|
|
body, err := a.buildRequest(req, false)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint(), bytes.NewReader(body))
|
|
if err != nil {
|
|
return Response{}, fmt.Errorf("model: %w: build request: %v", ErrUpstream, err)
|
|
}
|
|
resp, err := a.doRequest(httpReq, false)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return Response{}, a.upstreamError(resp)
|
|
}
|
|
var wire openAIChatResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&wire); err != nil {
|
|
return Response{}, fmt.Errorf("model: %w: decode response: %v", ErrUpstream, err)
|
|
}
|
|
out := responseFromWire(&wire)
|
|
a.record(req, start, out.TotalTokens)
|
|
return out, nil
|
|
}
|
|
|
|
// ChatStream streams structured events via onEvent and returns the aggregated
|
|
// response with usage when the provider reports it in the final chunk.
|
|
func (a *OpenAIChatAdapter) ChatStream(ctx context.Context, req Request, onEvent func(StreamEvent)) (Response, error) {
|
|
start := time.Now()
|
|
if a.baseURL == "" {
|
|
return Response{}, ErrUpstream
|
|
}
|
|
model, err := a.resolveModel(req)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
req.Model = model
|
|
body, err := a.buildRequest(req, true)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint(), bytes.NewReader(body))
|
|
if err != nil {
|
|
return Response{}, fmt.Errorf("model: %w: build request: %v", ErrUpstream, err)
|
|
}
|
|
resp, err := a.doRequest(httpReq, true)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return Response{}, a.upstreamError(resp)
|
|
}
|
|
out, err := scanSSE(resp.Body, onEvent)
|
|
if err != nil {
|
|
return Response{}, err
|
|
}
|
|
out.Model = model
|
|
a.record(req, start, out.TotalTokens)
|
|
return out, nil
|
|
}
|
|
|
|
// withCallTimeout wraps ctx with opts.Timeout when it is positive.
|
|
func withCallTimeout(parent context.Context, opts Options) (context.Context, context.CancelFunc) {
|
|
if opts.Timeout > 0 {
|
|
return context.WithTimeout(parent, opts.Timeout)
|
|
}
|
|
return parent, func() {}
|
|
}
|
|
|
|
// resolveModel returns the effective model name.
|
|
func (a *OpenAIChatAdapter) resolveModel(req Request) (string, error) {
|
|
if req.Model != "" {
|
|
return req.Model, nil
|
|
}
|
|
if a.model != "" {
|
|
return a.model, nil
|
|
}
|
|
return "", ErrNoModel
|
|
}
|
|
|
|
// endpoint returns the full /chat/completions URL.
|
|
func (a *OpenAIChatAdapter) endpoint() string {
|
|
return a.baseURL + "/chat/completions"
|
|
}
|
|
|
|
func (a *OpenAIChatAdapter) doRequest(httpReq *http.Request, stream bool) (*http.Response, error) {
|
|
if a.apiKey != "" {
|
|
httpReq.Header.Set("Authorization", "Bearer "+a.apiKey)
|
|
}
|
|
httpReq.Header.Set("Content-Type", "application/json")
|
|
if stream {
|
|
httpReq.Header.Set("Accept", "text/event-stream")
|
|
} else {
|
|
httpReq.Header.Set("Accept", "application/json")
|
|
}
|
|
resp, err := a.client.Do(httpReq)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("model: %w: %v", ErrUpstream, err)
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
func (a *OpenAIChatAdapter) upstreamError(resp *http.Response) error {
|
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyCap))
|
|
return fmt.Errorf("model: %w: status %d: %s", ErrUpstream, resp.StatusCode, strings.TrimSpace(string(snippet)))
|
|
}
|
|
|
|
func (a *OpenAIChatAdapter) record(req Request, start time.Time, tokens int) {
|
|
if a.recorder == nil {
|
|
return
|
|
}
|
|
a.recorder(CallRecord{
|
|
Model: req.Model,
|
|
Purpose: req.Purpose,
|
|
Tokens: tokens,
|
|
TookMs: time.Since(start).Milliseconds(),
|
|
})
|
|
}
|