feat(logger): implement LLM debug logging functionality

- Added a new logger for LLM calls, enabling detailed logging of model interactions, including request and response data.
- Introduced configuration options for enabling and specifying the log directory for LLM debug logs.
- Implemented cleanup for old log files to manage disk space effectively.
- Wrapped existing chat implementations to log calls when debug logging is enabled, enhancing traceability for model interactions.
This commit is contained in:
wizardchen
2026-04-16 22:39:10 +08:00
committed by lyingbug
parent 6235a82183
commit 53e8e17df4
22 changed files with 1304 additions and 265 deletions
+5 -2
View File
@@ -107,14 +107,17 @@ type ChatConfig struct {
// NewChat 创建聊天实例
func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, error) {
var c Chat
var err error
switch strings.ToLower(string(config.Source)) {
case string(types.ModelSourceLocal):
return NewOllamaChat(config, ollamaService)
c, err = NewOllamaChat(config, ollamaService)
case string(types.ModelSourceRemote):
return NewRemoteChat(config)
c, err = NewRemoteChat(config)
default:
return nil, fmt.Errorf("unsupported chat model source: %s", config.Source)
}
return wrapChatDebug(c, err)
}
// NewRemoteChat 根据 provider 创建远程聊天实例
+214
View File
@@ -0,0 +1,214 @@
package chat
import (
"context"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
func buildLLMMessages(messages []Message) []logger.LLMMessage {
out := make([]logger.LLMMessage, 0, len(messages))
for _, m := range messages {
lm := logger.LLMMessage{
Role: m.Role,
Content: m.Content,
Name: m.Name,
ToolCallID: m.ToolCallID,
Images: m.Images,
}
if lm.Content == "" && len(m.MultiContent) > 0 {
var parts []string
for _, mc := range m.MultiContent {
switch mc.Type {
case "text":
parts = append(parts, mc.Text)
case "image_url":
if mc.ImageURL != nil {
parts = append(parts, fmt.Sprintf("[image_url: %s]", truncateForDebug(mc.ImageURL.URL, 120)))
}
}
}
lm.Content = strings.Join(parts, "\n")
}
for _, tc := range m.ToolCalls {
lm.ToolCalls = append(lm.ToolCalls, logger.LLMToolCallInfo{
ID: tc.ID,
FuncName: tc.Function.Name,
Arguments: tc.Function.Arguments,
})
}
out = append(out, lm)
}
return out
}
func buildOptionsSection(opts *ChatOptions) string {
if opts == nil {
return ""
}
var parts []string
parts = append(parts, fmt.Sprintf("Temperature=%.2f", opts.Temperature))
if opts.TopP > 0 {
parts = append(parts, fmt.Sprintf("TopP=%.2f", opts.TopP))
}
if opts.MaxTokens > 0 {
parts = append(parts, fmt.Sprintf("MaxTokens=%d", opts.MaxTokens))
}
if opts.MaxCompletionTokens > 0 {
parts = append(parts, fmt.Sprintf("MaxCompletionTokens=%d", opts.MaxCompletionTokens))
}
if opts.FrequencyPenalty > 0 {
parts = append(parts, fmt.Sprintf("FrequencyPenalty=%.2f", opts.FrequencyPenalty))
}
if opts.PresencePenalty > 0 {
parts = append(parts, fmt.Sprintf("PresencePenalty=%.2f", opts.PresencePenalty))
}
if opts.ToolChoice != "" {
parts = append(parts, fmt.Sprintf("ToolChoice=%s", opts.ToolChoice))
}
if len(opts.Format) > 0 {
parts = append(parts, "ResponseFormat=json_object")
}
return strings.Join(parts, ", ")
}
func buildToolsSection(opts *ChatOptions) string {
if opts == nil || len(opts.Tools) == 0 {
return ""
}
var b strings.Builder
for i, t := range opts.Tools {
if i > 0 {
b.WriteString("\n")
}
b.WriteString(fmt.Sprintf("- %s: %s", t.Function.Name, t.Function.Description))
}
return b.String()
}
func buildResponseToolCalls(tcs []types.LLMToolCall) []logger.LLMToolCallInfo {
if len(tcs) == 0 {
return nil
}
out := make([]logger.LLMToolCallInfo, 0, len(tcs))
for _, tc := range tcs {
out = append(out, logger.LLMToolCallInfo{
ID: tc.ID,
FuncName: tc.Function.Name,
Arguments: tc.Function.Arguments,
})
}
return out
}
func usageString(u types.TokenUsage) string {
return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d",
u.PromptTokens, u.CompletionTokens, u.TotalTokens)
}
// logLLMDebugCall logs a complete non-stream LLM chat call.
func logLLMDebugCall(ctx context.Context, model string, messages []Message, opts *ChatOptions, resp *types.ChatResponse, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Chat",
Model: model,
Duration: dur,
}
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Messages",
Content: logger.FormatMessages(buildLLMMessages(messages)),
})
if s := buildOptionsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s})
}
if s := buildToolsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s})
}
if resp != nil {
var respText strings.Builder
if resp.Content != "" {
respText.WriteString("[assistant]\n")
respText.WriteString(resp.Content)
respText.WriteString("\n")
}
tcs := buildResponseToolCalls(resp.ToolCalls)
if len(tcs) > 0 {
respText.WriteString(logger.FormatToolCalls(tcs))
}
if respText.Len() > 0 {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()})
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(resp.Usage)})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
// logLLMDebugStream logs a complete stream LLM chat call after all chunks have been received.
func logLLMDebugStream(ctx context.Context, model string, messages []Message, opts *ChatOptions, fullContent string, toolCalls []types.LLMToolCall, usage *types.TokenUsage, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Chat Stream",
Model: model,
Duration: dur,
}
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Messages",
Content: logger.FormatMessages(buildLLMMessages(messages)),
})
if s := buildOptionsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s})
}
if s := buildToolsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s})
}
var respText strings.Builder
if fullContent != "" {
respText.WriteString("[assistant]\n")
respText.WriteString(fullContent)
respText.WriteString("\n")
}
tcs := buildResponseToolCalls(toolCalls)
if len(tcs) > 0 {
respText.WriteString(logger.FormatToolCalls(tcs))
}
if respText.Len() > 0 {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()})
}
if usage != nil {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(*usage)})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
func truncateForDebug(s string, maxRunes int) string {
runes := []rune(s)
if len(runes) <= maxRunes {
return s
}
return string(runes[:maxRunes]) + fmt.Sprintf("...(%d chars)", len(runes))
}
+77
View File
@@ -0,0 +1,77 @@
package chat
import (
"context"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// debugChat wraps a Chat implementation and logs all calls to the LLM debug log.
// It works with both RemoteAPIChat and OllamaChat (or any future Chat impl).
type debugChat struct {
inner Chat
}
func (d *debugChat) GetModelName() string { return d.inner.GetModelName() }
func (d *debugChat) GetModelID() string { return d.inner.GetModelID() }
func (d *debugChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
callStart := time.Now()
resp, err := d.inner.Chat(ctx, messages, opts)
logLLMDebugCall(ctx, d.inner.GetModelName(), messages, opts, resp, err, time.Since(callStart))
return resp, err
}
func (d *debugChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
callStart := time.Now()
ch, err := d.inner.ChatStream(ctx, messages, opts)
if err != nil {
logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, "", nil, nil, err, time.Since(callStart))
return ch, err
}
if ch == nil {
return nil, nil
}
wrapped := make(chan types.StreamResponse)
go func() {
defer close(wrapped)
var content strings.Builder
var usage *types.TokenUsage
var toolCalls []types.LLMToolCall
var streamErr error
for resp := range ch {
if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" {
content.WriteString(resp.Content)
}
if resp.ResponseType == types.ResponseTypeError {
streamErr = fmt.Errorf("%s", resp.Content)
}
if resp.Usage != nil {
usage = resp.Usage
}
if len(resp.ToolCalls) > 0 {
toolCalls = resp.ToolCalls
}
wrapped <- resp
}
logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts,
content.String(), toolCalls, usage, streamErr, time.Since(callStart))
}()
return wrapped, nil
}
// wrapChatDebug wraps a Chat if LLM debug logging is enabled.
func wrapChatDebug(c Chat, err error) (Chat, error) {
if err != nil || !logger.LLMDebugEnabled() {
return c, err
}
return &debugChat{inner: c}, nil
}
+6 -4
View File
@@ -570,11 +570,12 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens)
}
toolCalls := state.buildOrderedToolCalls()
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
Done: true,
ToolCalls: state.buildOrderedToolCalls(),
ToolCalls: toolCalls,
Usage: state.usage,
FinishReason: state.lastFinishReason,
}
@@ -614,16 +615,16 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
event, err := reader.ReadEvent()
if err != nil {
if err == io.EOF {
// 部分模型不发送 [DONE] 标记,直接关闭连接,视为正常结束
if state.usage != nil {
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens)
}
toolCalls := state.buildOrderedToolCalls()
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
Done: true,
ToolCalls: state.buildOrderedToolCalls(),
ToolCalls: toolCalls,
Usage: state.usage,
}
} else {
@@ -646,11 +647,12 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens)
}
toolCalls := state.buildOrderedToolCalls()
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
Done: true,
ToolCalls: state.buildOrderedToolCalls(),
ToolCalls: toolCalls,
Usage: state.usage,
}
return
+9
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/types"
@@ -54,6 +55,14 @@ type Config struct {
// NewEmbedder creates an embedder based on the configuration
func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
e, err := newEmbedder(config, pooler, ollamaService)
if err != nil || !logger.LLMDebugEnabled() {
return e, err
}
return &debugEmbedder{inner: e}, nil
}
func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
var embedder Embedder
var err error
switch strings.ToLower(string(config.Source)) {
+93
View File
@@ -0,0 +1,93 @@
package embedding
import (
"context"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// debugEmbedder wraps an Embedder with LLM debug logging.
type debugEmbedder struct {
inner Embedder
}
func (d *debugEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
start := time.Now()
result, err := d.inner.Embed(ctx, text)
logEmbeddingDebug(ctx, d.inner.GetModelName(), []string{text}, singleToDouble(result), err, time.Since(start))
return result, err
}
func (d *debugEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
start := time.Now()
result, err := d.inner.BatchEmbed(ctx, texts)
logEmbeddingDebug(ctx, d.inner.GetModelName(), texts, result, err, time.Since(start))
return result, err
}
func (d *debugEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
return d.inner.BatchEmbedWithPool(ctx, d, texts)
}
func (d *debugEmbedder) GetModelName() string { return d.inner.GetModelName() }
func (d *debugEmbedder) GetDimensions() int { return d.inner.GetDimensions() }
func (d *debugEmbedder) GetModelID() string { return d.inner.GetModelID() }
func singleToDouble(v []float32) [][]float32 {
if v == nil {
return nil
}
return [][]float32{v}
}
func logEmbeddingDebug(ctx context.Context, model string, inputs []string, outputs [][]float32, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Embedding",
Model: model,
Duration: dur,
}
// Input section: show each text with a preview
var inputBuf strings.Builder
inputBuf.WriteString(fmt.Sprintf("count=%d\n", len(inputs)))
for i, t := range inputs {
preview := strings.ReplaceAll(t, "\n", "\\n")
preview = logger.TruncateRunes(preview, 200)
inputBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(t)), preview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()})
// Output section
if outputs != nil {
var outBuf strings.Builder
outBuf.WriteString(fmt.Sprintf("count=%d\n", len(outputs)))
for i, vec := range outputs {
if len(vec) > 0 {
outBuf.WriteString(fmt.Sprintf("[%d] dims=%d, first_3=[%.6f, %.6f, %.6f]\n", i, len(vec),
safeIdx(vec, 0), safeIdx(vec, 1), safeIdx(vec, 2)))
} else {
outBuf.WriteString(fmt.Sprintf("[%d] empty\n", i))
}
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Output", Content: outBuf.String()})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
func safeIdx(v []float32, i int) float32 {
if i < len(v) {
return v[i]
}
return 0
}
+70
View File
@@ -0,0 +1,70 @@
package rerank
import (
"context"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// debugReranker wraps a Reranker with LLM debug logging.
type debugReranker struct {
inner Reranker
}
func (d *debugReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
start := time.Now()
result, err := d.inner.Rerank(ctx, query, documents)
logRerankDebug(ctx, d.inner.GetModelName(), query, documents, result, err, time.Since(start))
return result, err
}
func (d *debugReranker) GetModelName() string { return d.inner.GetModelName() }
func (d *debugReranker) GetModelID() string { return d.inner.GetModelID() }
func logRerankDebug(ctx context.Context, model string, query string, documents []string, results []RankResult, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Rerank",
Model: model,
Duration: dur,
}
// Query section
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Query",
Content: query,
})
// Documents section
var docBuf strings.Builder
docBuf.WriteString(fmt.Sprintf("count=%d\n", len(documents)))
for i, doc := range documents {
preview := strings.ReplaceAll(doc, "\n", "\\n")
preview = logger.TruncateRunes(preview, 200)
docBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(doc)), preview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Documents", Content: docBuf.String()})
// Results section
if results != nil {
var resBuf strings.Builder
resBuf.WriteString(fmt.Sprintf("count=%d\n", len(results)))
for _, r := range results {
docPreview := strings.ReplaceAll(r.Document.Text, "\n", "\\n")
docPreview = logger.TruncateRunes(docPreview, 200)
resBuf.WriteString(fmt.Sprintf(" [%d] score=%.6f %s\n", r.Index, r.RelevanceScore, docPreview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Results", Content: resBuf.String()})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
+9
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -91,6 +92,14 @@ type RerankerConfig struct {
// NewReranker creates a reranker based on the configuration
func NewReranker(config *RerankerConfig) (Reranker, error) {
r, err := newReranker(config)
if err != nil || !logger.LLMDebugEnabled() {
return r, err
}
return &debugReranker{inner: r}, nil
}
func newReranker(config *RerankerConfig) (Reranker, error) {
// Use provider field if set, otherwise detect from URL using provider registry
providerName := provider.ProviderName(config.Provider)
if providerName == "" {
+63
View File
@@ -0,0 +1,63 @@
package vlm
import (
"context"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// debugVLM wraps a VLM with LLM debug logging.
type debugVLM struct {
inner VLM
}
func (d *debugVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
start := time.Now()
result, err := d.inner.Predict(ctx, imgBytes, prompt)
logVLMDebug(ctx, d.inner.GetModelName(), imgBytes, prompt, result, err, time.Since(start))
return result, err
}
func (d *debugVLM) GetModelName() string { return d.inner.GetModelName() }
func (d *debugVLM) GetModelID() string { return d.inner.GetModelID() }
func logVLMDebug(ctx context.Context, model string, imgBytes [][]byte, prompt string, response string, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "VLM",
Model: model,
Duration: dur,
}
// Input section
var inputBuf strings.Builder
inputBuf.WriteString(fmt.Sprintf("Images: count=%d", len(imgBytes)))
totalSize := 0
for _, img := range imgBytes {
totalSize += len(img)
}
inputBuf.WriteString(fmt.Sprintf(", total_size=%d bytes\n\n", totalSize))
inputBuf.WriteString("[prompt]\n")
inputBuf.WriteString(prompt)
inputBuf.WriteString("\n")
record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()})
// Response section
if response != "" {
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Response",
Content: response,
})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
+9
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/types"
@@ -35,6 +36,14 @@ type Config struct {
// NewVLM creates a VLM instance based on the provided configuration.
func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
v, err := newVLM(config, ollamaService)
if err != nil || !logger.LLMDebugEnabled() {
return v, err
}
return &debugVLM{inner: v}, nil
}
func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
ifType := strings.ToLower(config.InterfaceType)
if ifType == "ollama" || config.Source == types.ModelSourceLocal {