更新若干功能

This commit is contained in:
李琦
2026-08-14 07:52:01 +08:00
parent 153c7ed448
commit 89bc265f68
196 changed files with 17675 additions and 0 deletions

68
service/ai/ai_test.go Normal file
View File

@@ -0,0 +1,68 @@
package ai
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestFactory(t *testing.T) {
if _, e := New("bogus", "k"); e == nil || e.Error() != "AI_PROVIDER_INVALID" {
t.Fatalf("expected AI_PROVIDER_INVALID, got %v", e)
}
if _, e := New(ProviderSpark, ""); e == nil || e.Error() != "AI_KEY_MISSING" {
t.Fatalf("expected AI_KEY_MISSING, got %v", e)
}
p, e := New(ProviderDeepSeek, "key")
if e != nil || p.Name() != ProviderDeepSeek {
t.Fatalf("unexpected: %v %v", p, e)
}
p, e = New(ProviderSpark, "key")
if e != nil || p.Name() != ProviderSpark {
t.Fatalf("unexpected: %v %v", p, e)
}
}
func TestChatStreamSSE(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/chat/completions" {
t.Errorf("unexpected path %s", r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "Bearer test-key" {
t.Errorf("unexpected auth header %q", got)
}
w.Header().Set("Content-Type", "text/event-stream")
w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\n"))
w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\",世界\"}}]}\n\n"))
w.Write([]byte("data: [DONE]\n\n"))
}))
defer srv.Close()
p := &openAICompatible{name: "test", baseURL: srv.URL, model: "m", apiKey: "test-key", client: srv.Client()}
stream, e := p.ChatStream(context.Background(), []Message{{Role: "user", Content: "hi"}})
if e != nil {
t.Fatal(e)
}
var sb strings.Builder
for c := range stream {
if c.Err != nil {
t.Fatal(c.Err)
}
sb.WriteString(c.Content)
}
if sb.String() != "你好,世界" {
t.Fatalf("unexpected content %q", sb.String())
}
}
func TestChatStreamAuthError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()
p := &openAICompatible{name: "test", baseURL: srv.URL, model: "m", apiKey: "bad", client: srv.Client()}
if _, e := p.ChatStream(context.Background(), nil); e == nil || e.Error() != "AI_KEY_INVALID" {
t.Fatalf("expected AI_KEY_INVALID, got %v", e)
}
}

49
service/ai/factory.go Normal file
View File

@@ -0,0 +1,49 @@
package ai
import "errors"
// 支持的 Provider 标识。
const (
ProviderSpark = "spark"
ProviderDeepSeek = "deepseek"
)
// New 是 Provider 工厂:按标识与 API Key 创建对应实例。
func New(provider, apiKey string) (Provider, error) {
switch provider {
case ProviderSpark:
return newSpark(apiKey)
case ProviderDeepSeek:
return newDeepSeek(apiKey)
default:
return nil, errors.New("AI_PROVIDER_INVALID")
}
}
// newSpark 创建讯飞星火 LiteOpenAI 兼容 HTTP 端点APIPassword 鉴权Lite 免费)。
func newSpark(apiPassword string) (Provider, error) {
if apiPassword == "" {
return nil, errors.New("AI_KEY_MISSING")
}
return &openAICompatible{
name: ProviderSpark,
baseURL: "https://spark-api-open.xf-yun.com/v1",
model: "lite",
apiKey: apiPassword,
client: newHTTPClient(),
}, nil
}
// newDeepSeek 创建 DeepSeekOpenAI 兼容)。
func newDeepSeek(apiKey string) (Provider, error) {
if apiKey == "" {
return nil, errors.New("AI_KEY_MISSING")
}
return &openAICompatible{
name: ProviderDeepSeek,
baseURL: "https://api.deepseek.com",
model: "deepseek-chat",
apiKey: apiKey,
client: newHTTPClient(),
}, nil
}

117
service/ai/openai.go Normal file
View File

@@ -0,0 +1,117 @@
package ai
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// openAICompatible 是 OpenAI Chat Completions 兼容端点的通用流式客户端;
// 讯飞星火 Lite 与 DeepSeek 均暴露该协议,只是 baseURL/model/key 不同。
type openAICompatible struct {
name string
baseURL string
model string
apiKey string
client *http.Client
}
func (p *openAICompatible) Name() string { return p.name }
type chatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Stream bool `json:"stream"`
}
type chatDelta struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
func (p *openAICompatible) ChatStream(ctx context.Context, messages []Message) (<-chan Chunk, error) {
body, e := json.Marshal(chatRequest{Model: p.model, Messages: messages, Stream: true})
if e != nil {
return nil, e
}
req, e := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(p.baseURL, "/")+"/chat/completions", bytes.NewReader(body))
if e != nil {
return nil, e
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+p.apiKey)
req.Header.Set("Accept", "text/event-stream")
resp, e := p.client.Do(req)
if e != nil {
return nil, errors.New("AI_NETWORK_ERROR")
}
if resp.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return nil, errors.New("AI_KEY_INVALID")
}
return nil, fmt.Errorf("AI_HTTP_%d: %s", resp.StatusCode, truncate(string(raw), 300))
}
out := make(chan Chunk, 16)
go func() {
defer close(out)
defer resp.Body.Close()
sc := bufio.NewScanner(resp.Body)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if !strings.HasPrefix(line, "data:") {
continue
}
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if payload == "" || payload == "[DONE]" {
continue
}
var d chatDelta
if json.Unmarshal([]byte(payload), &d) != nil {
continue
}
if d.Error != nil {
out <- Chunk{Err: errors.New(truncate(d.Error.Message, 300))}
return
}
if len(d.Choices) > 0 && d.Choices[0].Delta.Content != "" {
select {
case out <- Chunk{Content: d.Choices[0].Delta.Content}:
case <-ctx.Done():
return
}
}
}
if e := sc.Err(); e != nil && ctx.Err() == nil {
out <- Chunk{Err: errors.New("AI_STREAM_INTERRUPTED")}
}
}()
return out, nil
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
func newHTTPClient() *http.Client {
return &http.Client{Timeout: 5 * time.Minute}
}

24
service/ai/provider.go Normal file
View File

@@ -0,0 +1,24 @@
// Package ai 定义 AI 聊天 Provider 抽象与工厂:
// 上层只依赖 Provider 接口,通过 New 按设置创建讯飞星火 Lite 或 DeepSeek 实例。
package ai
import "context"
// Message 是一条对话消息role: system | user | assistant
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
// Chunk 是流式返回的一段增量内容Err 非空表示流异常中止。
type Chunk struct {
Content string
Err error
}
// Provider 是 AI 服务商的统一抽象。
type Provider interface {
Name() string
// ChatStream 发起流式对话,返回增量内容通道;通道关闭即流结束。
ChatStream(ctx context.Context, messages []Message) (<-chan Chunk, error)
}