feat(ops): ECR-007 行为分析与 ECR-008 内容运营后台
落地埋点 ingest/数据看板、首页宫格 CMS 与测评上下架;含账号引导、问答流式与免责声明去重,以及 review P1 审计同事务修复。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2,9 +2,11 @@
|
||||
package deepseek
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -60,6 +62,18 @@ type chatResponse struct {
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type streamChunk struct {
|
||||
Choices []struct {
|
||||
Delta struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"delta"`
|
||||
FinishReason *string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// Chat sends messages and returns assistant text.
|
||||
func (c *Client) Chat(ctx context.Context, messages []Message) (string, error) {
|
||||
if !c.Enabled() {
|
||||
@@ -110,6 +124,100 @@ func (c *Client) Chat(ctx context.Context, messages []Message) (string, error) {
|
||||
return strings.TrimSpace(out.Choices[0].Message.Content), nil
|
||||
}
|
||||
|
||||
// ChatStream streams assistant text; onDelta is called for each content piece.
|
||||
// Returns the full assembled reply.
|
||||
func (c *Client) ChatStream(ctx context.Context, messages []Message, onDelta func(delta string) error) (string, error) {
|
||||
if !c.Enabled() {
|
||||
return "", fmt.Errorf("deepseek api_key not configured")
|
||||
}
|
||||
if onDelta == nil {
|
||||
onDelta = func(string) error { return nil }
|
||||
}
|
||||
base := c.cfg.BaseURL
|
||||
if base == "" {
|
||||
base = "https://api.deepseek.com"
|
||||
}
|
||||
model := c.cfg.Model
|
||||
if model == "" {
|
||||
model = "deepseek-chat"
|
||||
}
|
||||
|
||||
body, err := json.Marshal(chatRequest{Model: model, Messages: messages, Stream: true})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/chat/completions", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
|
||||
// Stream may outlive the default client timeout; use a dedicated client.
|
||||
sec := c.cfg.TimeoutSec
|
||||
if sec <= 0 {
|
||||
sec = 90
|
||||
}
|
||||
httpClient := &http.Client{Timeout: time.Duration(sec) * time.Second}
|
||||
res, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode >= 300 {
|
||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 2<<20))
|
||||
return "", fmt.Errorf("deepseek HTTP %d: %s", res.StatusCode, truncate(string(raw), 200))
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(res.Body)
|
||||
var full strings.Builder
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
return full.String(), err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" || strings.HasPrefix(line, ":") {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
}
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if payload == "[DONE]" {
|
||||
break
|
||||
}
|
||||
var chunk streamChunk
|
||||
if err := json.Unmarshal([]byte(payload), &chunk); err != nil {
|
||||
continue
|
||||
}
|
||||
if chunk.Error != nil && chunk.Error.Message != "" {
|
||||
return full.String(), fmt.Errorf("deepseek: %s", chunk.Error.Message)
|
||||
}
|
||||
if len(chunk.Choices) == 0 {
|
||||
continue
|
||||
}
|
||||
delta := chunk.Choices[0].Delta.Content
|
||||
if delta == "" {
|
||||
continue
|
||||
}
|
||||
full.WriteString(delta)
|
||||
if err := onDelta(delta); err != nil {
|
||||
return full.String(), err
|
||||
}
|
||||
}
|
||||
out := strings.TrimSpace(full.String())
|
||||
if out == "" {
|
||||
return "", fmt.Errorf("deepseek empty stream")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
|
||||
@@ -40,8 +40,36 @@ func TestChat_success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnabled(t *testing.T) {
|
||||
if New(config.DeepSeekConfig{}).Enabled() {
|
||||
t.Fatal("empty key should disable")
|
||||
func TestChatStream_success(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var req chatRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
if !req.Stream {
|
||||
t.Fatal("expected stream=true")
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
flusher := w.(http.Flusher)
|
||||
_, _ = w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\n"))
|
||||
flusher.Flush()
|
||||
_, _ = w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"世界\"}}]}\n\n"))
|
||||
flusher.Flush()
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
flusher.Flush()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(config.DeepSeekConfig{
|
||||
APIKey: "test-key", BaseURL: srv.URL, Model: "deepseek-chat", TimeoutSec: 5,
|
||||
})
|
||||
var got string
|
||||
out, err := c.ChatStream(context.Background(), []Message{{Role: "user", Content: "hi"}}, func(d string) error {
|
||||
got += d
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "你好世界" || got != "你好世界" {
|
||||
t.Fatalf("out=%q got=%q", out, got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user