feat(prompt): enhance context and intent classification in templates

- Updated context template to include runtime metadata such as current time and week, improving contextual awareness in user queries.
- Enhanced rewrite template with critical instructions for intent classification, ensuring that rewritten questions preserve essential entities and keywords.
- Refined intent classification logic to prioritize user intents more effectively, improving the accuracy of responses based on user queries.
- Added examples to clarify expected input and output formats for intent classification, enhancing usability for developers.
This commit is contained in:
wizardchen
2026-03-26 16:45:51 +08:00
committed by lyingbug
parent 27d4525ba9
commit 72dfb9ce75
44 changed files with 451 additions and 135 deletions
+5 -2
View File
@@ -969,10 +969,13 @@ func (r *chunkRepository) ListRecentDocumentChunksWithQuestions(
Select("id, knowledge_base_id, chunk_type, metadata, updated_at").
Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ?",
tenantID, types.ChunkTypeText, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true)
if len(knowledgeIDs) > 0 {
if len(kbIDs) > 0 && len(knowledgeIDs) > 0 {
baseQuery = baseQuery.Where("knowledge_base_id IN ? OR knowledge_id IN ?", kbIDs, knowledgeIDs)
} else if len(knowledgeIDs) > 0 {
// 指定了具体知识文档,直接按 knowledge_id 过滤(忽略 kbIDs)
baseQuery = baseQuery.Where("knowledge_id IN ?", knowledgeIDs)
} else {
} else if len(kbIDs) > 0 {
baseQuery = baseQuery.Where("knowledge_base_id IN ?", kbIDs)
}
@@ -245,6 +245,14 @@ func (r *messageRepository) UpdateMessageImages(ctx context.Context, sessionID,
Update("images", images).Error
}
// UpdateMessageRenderedContent updates only the rendered_content column for a message.
func (r *messageRepository) UpdateMessageRenderedContent(ctx context.Context, sessionID, messageID string, renderedContent string) error {
return r.db.WithContext(ctx).
Model(&types.Message{}).
Where("id = ? AND session_id = ?", messageID, sessionID).
Update("rendered_content", renderedContent).Error
}
// DeleteMessagesBySessionID deletes all messages belonging to a session (soft delete)
func (r *messageRepository) DeleteMessagesBySessionID(ctx context.Context, sessionID string) error {
return r.db.WithContext(ctx).Where("session_id = ?", sessionID).Delete(&types.Message{}).Error
@@ -65,7 +65,11 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
if chatManage.SystemPromptOverride != "" {
base = chatManage.SystemPromptOverride
}
systemPrompt := renderSystemPromptPlaceholders(base, chatManage.Language)
systemPrompt := types.RenderPromptPlaceholders(base, types.PlaceholderValues{
"query": chatManage.Query,
"language": chatManage.Language,
"contexts": chatManage.RenderedContexts,
})
chatMessages := []chat.Message{
{Role: "system", Content: systemPrompt},
@@ -110,9 +114,13 @@ func loadAndProcessHistory(
h = &types.History{}
}
if message.Role == "user" {
h.Query = message.Content
if message.RenderedContent != "" {
h.Query = message.RenderedContent
} else {
h.Query = message.Content
}
h.CreateAt = message.CreatedAt
if desc := extractImageCaptions(message.Images); desc != "" {
if desc := extractImageCaptions(message.Images); desc != "" && message.RenderedContent == "" {
h.Query += "\n\n[用户上传图片内容]\n" + desc
}
} else {
@@ -154,18 +162,6 @@ func extractImageCaptions(images types.MessageImages) string {
return strings.Join(parts, "\n")
}
// renderSystemPromptPlaceholders replaces placeholders in system prompt
// Supported placeholders:
// - {{current_time}} -> current time in RFC3339 format
// - {{language}} -> user language name (replaced if present; empty string if not set in ChatManage)
func renderSystemPromptPlaceholders(prompt string, language ...string) string {
vals := types.PlaceholderValues{}
if len(language) > 0 {
vals["language"] = language[0]
}
return types.RenderPromptPlaceholders(prompt, vals)
}
// ---------------------------------------------------------------------------
// Concurrency utilities
// ---------------------------------------------------------------------------
@@ -141,8 +141,9 @@ Return your response in the specified JSON format.`, chatManage.Query, knowledge
Score: 1.0,
MatchType: types.MatchTypeDataAnalysis,
KnowledgeID: knowledge.ID,
KnowledgeTitle: knowledge.Title,
KnowledgeFilename: knowledge.FileName,
KnowledgeTitle: knowledge.Title,
KnowledgeFilename: knowledge.FileName,
KnowledgeDescription: knowledge.Description,
}
chatManage.MergeResult = append(chatManage.MergeResult, analysisResult)
@@ -8,15 +8,18 @@ import (
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
// PluginIntoChatMessage handles the transformation of search results into chat messages
type PluginIntoChatMessage struct{}
type PluginIntoChatMessage struct {
messageService interfaces.MessageService
}
// NewPluginIntoChatMessage creates and registers a new PluginIntoChatMessage instance
func NewPluginIntoChatMessage(eventManager *EventManager) *PluginIntoChatMessage {
res := &PluginIntoChatMessage{}
func NewPluginIntoChatMessage(eventManager *EventManager, messageService interfaces.MessageService) *PluginIntoChatMessage {
res := &PluginIntoChatMessage{messageService: messageService}
eventManager.Register(res)
return res
}
@@ -73,9 +76,9 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
return ErrTemplateExecute.WithError(fmt.Errorf("user query contains invalid content"))
}
// Intent-based no-search path: bypass "reference materials" template entirely.
// Intent-based no-search path: no retrieval results, but still render
// through the context template so runtime metadata (current_time, etc.) is injected.
if !chatManage.NeedsRetrieval() {
// Prefer rewritten query in no-search mode; fallback to original query.
userContent := safeQuery
if rewrite := strings.TrimSpace(chatManage.RewriteQuery); rewrite != "" {
if safeRewrite, ok := utils.ValidateInput(rewrite); ok {
@@ -89,16 +92,38 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
if chatManage.ImageDescription != "" && !chatManage.ChatModelSupportsVision {
userContent += "\n\n[用户上传图片内容]\n" + chatManage.ImageDescription
}
chatManage.UserContent = userContent
pipelineInfo(ctx, "IntoChatMessage", "skip_template_no_search", map[string]interface{}{
if tpl := chatManage.SummaryConfig.ContextTemplate; tpl != "" {
chatManage.UserContent = types.RenderPromptPlaceholders(tpl, types.PlaceholderValues{
"query": userContent,
"contexts": "",
"language": chatManage.Language,
})
} else {
chatManage.UserContent = userContent
}
pipelineInfo(ctx, "IntoChatMessage", "no_search_with_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_content_len": len(chatManage.UserContent),
"has_template": chatManage.SummaryConfig.ContextTemplate != "",
})
return next()
}
var contextsBuilder strings.Builder
// Collect unique document metadata (title + description), once per knowledge
allResults := chatManage.MergeResult
if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
allResults = append(faqResults, docResults...)
}
docHeader := buildDocumentHeader(allResults)
if docHeader != "" {
contextsBuilder.WriteString(docHeader)
contextsBuilder.WriteString("\n")
}
// Build contexts string based on FAQ priority strategy
if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
// Build structured context with FAQ prioritization
@@ -135,10 +160,12 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
}
}
chatManage.RenderedContexts = contextsBuilder.String()
// Replace placeholders in context template
userContent := types.RenderPromptPlaceholders(chatManage.SummaryConfig.ContextTemplate, types.PlaceholderValues{
"query": safeQuery,
"contexts": contextsBuilder.String(),
"contexts": chatManage.RenderedContexts,
"language": chatManage.Language,
})
@@ -158,9 +185,98 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
"image_description": chatManage.ImageDescription,
"chat_model_supports_vision": chatManage.ChatModelSupportsVision,
})
p.persistRenderedContent(ctx, chatManage)
return next()
}
// persistRenderedContent asynchronously writes the RAG-augmented UserContent back
// to the user message so that subsequent conversation turns can see the full
// retrieval context in history.
func (p *PluginIntoChatMessage) persistRenderedContent(ctx context.Context, chatManage *types.ChatManage) {
if chatManage.UserMessageID == "" || chatManage.UserContent == "" {
pipelineInfo(ctx, "IntoChatMessage", "persist_rendered_content_skip", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_message_id": chatManage.UserMessageID,
"has_user_content": chatManage.UserContent != "",
"reason": "empty_id_or_content",
})
return
}
if chatManage.UserContent == chatManage.Query {
return
}
pipelineInfo(ctx, "IntoChatMessage", "persist_rendered_content", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_message_id": chatManage.UserMessageID,
"rendered_content_len": len(chatManage.UserContent),
})
bgCtx := context.WithoutCancel(ctx)
go func() {
if err := p.messageService.UpdateMessageRenderedContent(
bgCtx, chatManage.SessionID, chatManage.UserMessageID, chatManage.UserContent,
); err != nil {
pipelineWarn(bgCtx, "IntoChatMessage", "persist_rendered_content_error", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_message_id": chatManage.UserMessageID,
"error": err.Error(),
})
}
}()
}
// buildDocumentHeader generates a document metadata section listing each unique
// knowledge document (by KnowledgeID) with its title and description.
// Returns an empty string when no meaningful metadata is available.
func buildDocumentHeader(results []*types.SearchResult) string {
type docMeta struct {
title string
description string
}
seen := make(map[string]struct{})
var docs []docMeta
for _, r := range results {
if r.KnowledgeID == "" {
continue
}
if _, ok := seen[r.KnowledgeID]; ok {
continue
}
seen[r.KnowledgeID] = struct{}{}
title := r.KnowledgeTitle
if title == "" {
title = r.KnowledgeFilename
}
if title == "" {
continue
}
docs = append(docs, docMeta{
title: title,
description: r.KnowledgeDescription,
})
}
if len(docs) == 0 {
return ""
}
var b strings.Builder
b.WriteString("### Referenced Documents\n")
for i, d := range docs {
// if d.description != "" {
// b.WriteString(fmt.Sprintf("%d. %s — %s\n", i+1, d.title, d.description))
// } else {
// b.WriteString(fmt.Sprintf("%d. %s\n", i+1, d.title))
// }
b.WriteString(fmt.Sprintf("%d. %s\n", i+1, d.title))
}
return b.String()
}
// getEnrichedPassageForChat 合并Content和ImageInfo的文本内容,为聊天消息准备
func getEnrichedPassageForChat(ctx context.Context, result *types.SearchResult) string {
// 如果没有图片信息,直接返回内容
@@ -18,7 +18,7 @@ func TestIntoChatMessage_NoKBRetrieval(t *testing.T) {
Intent: types.IntentChitchat,
},
}
plugin := &PluginIntoChatMessage{}
plugin := &PluginIntoChatMessage{messageService: nil}
nextCalled := false
err := plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
nextCalled = true
@@ -50,7 +50,7 @@ func TestIntoChatMessage_WithMergeResults(t *testing.T) {
},
},
}
plugin := &PluginIntoChatMessage{}
plugin := &PluginIntoChatMessage{messageService: nil}
nextCalled := false
err := plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
nextCalled = true
@@ -84,7 +84,7 @@ func TestIntoChatMessage_ImageDescriptionAppended(t *testing.T) {
ImageDescription: "a cat sitting on a mat",
},
}
plugin := &PluginIntoChatMessage{}
plugin := &PluginIntoChatMessage{messageService: nil}
_ = plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
return nil
})
@@ -109,7 +109,7 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context,
userMsg.Images = chatManage.Images
}
maxTokens := 60
maxTokens := 150
if useImages {
maxTokens = 500
}
+2 -2
View File
@@ -462,7 +462,7 @@ func (s *customAgentService) GetSuggestedQuestions(
// 2. Determine knowledge base scope
effectiveKBIDs := kbIDs
if len(effectiveKBIDs) == 0 {
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
// Use agent's KB configuration
switch agent.Config.KBSelectionMode {
case "all":
@@ -506,7 +506,7 @@ func (s *customAgentService) GetSuggestedQuestions(
// 3. Collect all candidate chunks from both FAQ and Document KBs,
// then sort by updated_at uniformly (not FAQ-first).
type candidate struct {
question types.SuggestedQuestion
question types.SuggestedQuestion
updatedAt time.Time
}
var candidates []candidate
@@ -270,9 +270,10 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
ChunkType: string(chunk.ChunkType),
ParentChunkID: chunk.ParentChunkID,
ImageInfo: chunk.ImageInfo,
KnowledgeFilename: knowledge.FileName,
KnowledgeSource: knowledge.Source,
KnowledgeChannel: knowledge.Channel,
KnowledgeFilename: knowledge.FileName,
KnowledgeSource: knowledge.Source,
KnowledgeChannel: knowledge.Channel,
KnowledgeDescription: knowledge.Description,
ChunkMetadata: chunk.Metadata,
MatchedContent: matchedContent,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
@@ -124,9 +124,13 @@ func (cm *contextManager) rebuildFromDB(ctx context.Context, sessionID string) (
}
switch msg.Role {
case "user":
p.query = msg.Content
if msg.RenderedContent != "" {
p.query = msg.RenderedContent
} else {
p.query = msg.Content
}
p.createdAt = msg.CreatedAt
if desc := extractImageCaptions(msg.Images); desc != "" {
if desc := extractImageCaptions(msg.Images); desc != "" && msg.RenderedContent == "" {
p.query += "\n\n[用户上传图片内容]\n" + desc
}
case "assistant":
+5
View File
@@ -246,6 +246,11 @@ func (s *messageService) UpdateMessageImages(ctx context.Context, sessionID, mes
return s.messageRepo.UpdateMessageImages(ctx, sessionID, messageID, images)
}
// UpdateMessageRenderedContent updates the rendered_content column for a user message.
func (s *messageService) UpdateMessageRenderedContent(ctx context.Context, sessionID, messageID string, renderedContent string) error {
return s.messageRepo.UpdateMessageRenderedContent(ctx, sessionID, messageID, renderedContent)
}
// DeleteMessage removes a message from a session, also cleaning up its Knowledge entry in the chat history KB.
func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {
logger.Info(ctx, "Start deleting message")
@@ -145,9 +145,7 @@ func (s *sessionService) applyAgentOverridesToChatManage(
if customAgent.Config.RerankTopK > 0 {
cm.RerankTopK = customAgent.Config.RerankTopK
}
if customAgent.Config.RerankThreshold > 0 {
cm.RerankThreshold = customAgent.Config.RerankThreshold
}
cm.RerankThreshold = customAgent.Config.RerankThreshold
if customAgent.Config.RerankModelID != "" {
cm.RerankModelID = customAgent.Config.RerankModelID
}
+2 -2
View File
@@ -408,8 +408,8 @@ func ValidateConfig(cfg *Config) error {
if cfg.Conversation.VectorThreshold < 0 || cfg.Conversation.VectorThreshold > 1 {
errs = append(errs, "conversation.vector_threshold must be between 0 and 1")
}
if cfg.Conversation.RerankThreshold < 0 || cfg.Conversation.RerankThreshold > 1 {
errs = append(errs, "conversation.rerank_threshold must be between 0 and 1")
if cfg.Conversation.RerankThreshold < -10 || cfg.Conversation.RerankThreshold > 10 {
errs = append(errs, "conversation.rerank_threshold must be between -10 and 10")
}
}
@@ -232,13 +232,14 @@ func (h *AgentStreamHandler) handleReferences(ctx context.Context, evt event.Eve
} else if refMap, ok := ref.(map[string]interface{}); ok {
// Parse from map if needed
searchResult := &types.SearchResult{
ID: getString(refMap, "id"),
Content: getString(refMap, "content"),
Score: getFloat64(refMap, "score"),
KnowledgeID: getString(refMap, "knowledge_id"),
KnowledgeTitle: getString(refMap, "knowledge_title"),
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
ID: getString(refMap, "id"),
Content: getString(refMap, "content"),
Score: getFloat64(refMap, "score"),
KnowledgeID: getString(refMap, "knowledge_id"),
KnowledgeTitle: getString(refMap, "knowledge_title"),
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
KnowledgeDescription: getString(refMap, "knowledge_description"),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
}
if meta, ok := refMap["metadata"].(map[string]interface{}); ok {
+4 -3
View File
@@ -124,9 +124,10 @@ func buildStreamResponse(evt interfaces.StreamEvent, requestID string) *types.St
ChunkType: getString(refMap, "chunk_type"),
ParentChunkID: getString(refMap, "parent_chunk_id"),
ImageInfo: getString(refMap, "image_info"),
KnowledgeFilename: getString(refMap, "knowledge_filename"),
KnowledgeSource: getString(refMap, "knowledge_source"),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
KnowledgeFilename: getString(refMap, "knowledge_filename"),
KnowledgeSource: getString(refMap, "knowledge_source"),
KnowledgeDescription: getString(refMap, "knowledge_description"),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
}
searchResults = append(searchResults, sr)
}
+4 -4
View File
@@ -904,8 +904,8 @@ func validateConversationConfig(req *types.ConversationConfig) error {
if req.RerankTopK <= 0 {
return errors.NewBadRequestError("rerank_top_k must be greater than 0")
}
if req.RerankThreshold < 0 || req.RerankThreshold > 1 {
return errors.NewBadRequestError("rerank_threshold must be between 0 and 1")
if req.RerankThreshold < -10 || req.RerankThreshold > 10 {
return errors.NewBadRequestError("rerank_threshold must be between -10 and 10")
}
if req.Temperature < 0 || req.Temperature > 2 {
return errors.NewBadRequestError("temperature must be between 0 and 2")
@@ -1176,8 +1176,8 @@ func (h *TenantHandler) updateTenantRetrievalConfigInternal(c *gin.Context) {
c.Error(errors.NewBadRequestError("keyword_threshold must be between 0 and 1"))
return
}
if cfg.RerankThreshold < 0 || cfg.RerankThreshold > 1 {
c.Error(errors.NewBadRequestError("rerank_threshold must be between 0 and 1"))
if cfg.RerankThreshold < -10 || cfg.RerankThreshold > 10 {
c.Error(errors.NewBadRequestError("rerank_threshold must be between -10 and 10"))
return
}
if cfg.EmbeddingTopK < 0 || cfg.EmbeddingTopK > 200 {
+13 -4
View File
@@ -26,8 +26,16 @@ type loggerResponseBodyWriter struct {
}
// Write 重写Write方法,同时写入buffer和原始writer
// 限制buffer大小,避免SSE等流式响应导致内存无限增长
func (r loggerResponseBodyWriter) Write(b []byte) (int, error) {
r.body.Write(b)
if r.body.Len() < maxBodySize {
remaining := maxBodySize - r.body.Len()
if len(b) <= remaining {
r.body.Write(b)
} else {
r.body.Write(b[:remaining])
}
}
return r.ResponseWriter.Write(b)
}
@@ -182,12 +190,13 @@ func Logger() gin.HandlerFunc {
// 读取响应体
responseBodyStr := ""
if responseBody.Len() > 0 {
// 检查Content-Type,只记录JSON类型
contentType := c.Writer.Header().Get("Content-Type")
if strings.Contains(contentType, "application/json") ||
if strings.Contains(contentType, "text/event-stream") {
responseBodyStr = "[SSE流式响应,已跳过]"
} else if strings.Contains(contentType, "application/json") ||
strings.Contains(contentType, "text/") {
bodyBytes := responseBody.Bytes()
if len(bodyBytes) > maxBodySize {
if len(bodyBytes) >= maxBodySize {
responseBodyStr = string(bodyBytes[:maxBodySize]) + "... [内容过长,已截断]"
} else {
responseBodyStr = string(bodyBytes)
+7 -2
View File
@@ -156,14 +156,17 @@ func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOpt
return nil, fmt.Errorf("聊天请求失败: %w", err)
}
// 构建响应
totalTokens := promptTokens + completionTokens
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, promptTokens, completionTokens, totalTokens)
return &types.ChatResponse{
Content: responseContent,
ToolCalls: toolCalls,
Usage: types.TokenUsage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
TotalTokens: totalTokens,
},
}, nil
}
@@ -275,6 +278,8 @@ func (c *OllamaChat) ChatStream(
CompletionTokens: resp.EvalCount,
TotalTokens: resp.PromptEvalCount + resp.EvalCount,
}
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, usage.PromptTokens, usage.CompletionTokens, usage.TotalTokens)
}
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
+23 -3
View File
@@ -287,7 +287,13 @@ func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *Chat
}
}
return c.parseCompletionResponse(&resp)
result, err := c.parseCompletionResponse(&resp)
if err != nil {
return nil, err
}
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, result.Usage.PromptTokens, result.Usage.CompletionTokens, result.Usage.TotalTokens)
return result, nil
}
// chatWithRawHTTP 使用原始 HTTP 请求进行聊天(供自定义请求使用)
@@ -297,7 +303,7 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu
return nil, fmt.Errorf("marshal request: %w", err)
}
logger.Infof(ctx, "[LLM Request] model=%s, raw HTTP request:\n%s", c.modelName, string(jsonData))
logger.Infof(ctx, "[LLM Request] model=%s, raw HTTP request:\n%s", c.modelName, secutils.CompactImageDataURLForLog(string(jsonData)))
if endpoint == "" {
endpoint = c.baseURL + "/chat/completions"
}
@@ -328,7 +334,13 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu
return nil, fmt.Errorf("decode response: %w", err)
}
return c.parseCompletionResponse(&chatResp)
result, err := c.parseCompletionResponse(&chatResp)
if err != nil {
return nil, err
}
logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d",
c.modelName, result.Usage.PromptTokens, result.Usage.CompletionTokens, result.Usage.TotalTokens)
return result, nil
}
// parseCompletionResponse 解析非流式响应
@@ -488,6 +500,10 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
response, err := stream.Recv()
if err != nil {
if err == io.EOF {
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)
}
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
@@ -546,6 +562,10 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
}
if event.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)
}
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
+2
View File
@@ -93,6 +93,7 @@ type PipelineState struct {
EntityKnowledge map[string]string `json:"-"`
GraphResult *GraphData `json:"-"`
UserContent string `json:"-"`
RenderedContexts string `json:"-"`
ChatResponse *ChatResponse `json:"-"`
ImageDescription string `json:"-"`
SystemPromptOverride string `json:"-"`
@@ -189,6 +190,7 @@ func (c *ChatManage) Clone() *ChatManage {
Intent: c.Intent,
ImageDescription: c.ImageDescription,
SystemPromptOverride: c.SystemPromptOverride,
RenderedContexts: c.RenderedContexts,
},
}
}
-3
View File
@@ -238,9 +238,6 @@ func (a *CustomAgent) EnsureDefaults() {
if a.Config.RerankTopK == 0 {
a.Config.RerankTopK = 5
}
if a.Config.RerankThreshold == 0 {
a.Config.RerankThreshold = 0.5
}
// Advanced settings defaults
if a.Config.FallbackStrategy == "" {
a.Config.FallbackStrategy = "model"
+5
View File
@@ -32,6 +32,9 @@ type MessageService interface {
// UpdateMessageImages updates only the images JSONB column for a message.
UpdateMessageImages(ctx context.Context, sessionID, messageID string, images types.MessageImages) error
// UpdateMessageRenderedContent updates the rendered_content column for a user message.
UpdateMessageRenderedContent(ctx context.Context, sessionID, messageID string, renderedContent string) error
// DeleteMessage deletes a message
DeleteMessage(ctx context.Context, sessionID string, id string) error
@@ -74,6 +77,8 @@ type MessageRepository interface {
UpdateMessage(ctx context.Context, message *types.Message) error
// UpdateMessageImages updates only the images JSONB column for a message
UpdateMessageImages(ctx context.Context, sessionID, messageID string, images types.MessageImages) error
// UpdateMessageRenderedContent updates the rendered_content column for a user message
UpdateMessageRenderedContent(ctx context.Context, sessionID, messageID string, renderedContent string) error
// DeleteMessage deletes a message
DeleteMessage(ctx context.Context, sessionID string, id string) error
// DeleteMessagesBySessionID deletes all messages belonging to a session
+5 -1
View File
@@ -125,8 +125,12 @@ type Message struct {
IsFallback bool `json:"is_fallback,omitempty"`
// Agent total execution duration in milliseconds (from query start to answer start)
AgentDurationMs int64 `json:"agent_duration_ms,omitempty" gorm:"column:agent_duration_ms;default:0"`
// RenderedContent stores the full RAG-augmented user message (with retrieved context)
// sent to the LLM. Used to preserve retrieval context across conversation turns.
// Empty for non-retrieval intents or assistant messages.
RenderedContent string `json:"-" gorm:"type:text;column:rendered_content;default:''"`
// Channel indicates the source channel of this message (e.g., "web", "api", "im")
Channel string `json:"channel,omitempty" gorm:"type:varchar(50);default:''"`
Channel string `json:"channel,omitempty" gorm:"type:varchar(50);default:''"`
// KnowledgeID links this message to a Knowledge entry in the chat history knowledge base
// Used for vector search indexing: when set, the message content has been indexed as a Knowledge passage
KnowledgeID string `json:"knowledge_id,omitempty" gorm:"type:varchar(36);index"`
+2 -2
View File
@@ -20,7 +20,7 @@ type RetrievalConfig struct {
KeywordThreshold float64 `json:"keyword_threshold"`
// RerankTopK is the maximum number of results after reranking (default: 10)
RerankTopK int `json:"rerank_top_k"`
// RerankThreshold is the minimum rerank score (0-1, default: 0.2)
// RerankThreshold is the minimum rerank score (-10 to 10, default: 0.2)
RerankThreshold float64 `json:"rerank_threshold"`
// RerankModelID is the ID of the rerank model to use (required for search)
RerankModelID string `json:"rerank_model_id"`
@@ -60,7 +60,7 @@ func (c *RetrievalConfig) GetEffectiveRerankTopK() int {
// GetEffectiveRerankThreshold returns RerankThreshold with a fallback default.
func (c *RetrievalConfig) GetEffectiveRerankThreshold() float64 {
if c == nil || c.RerankThreshold <= 0 {
if c == nil {
return 0.2
}
return c.RerankThreshold
+3
View File
@@ -130,6 +130,9 @@ type SearchResult struct {
// For FAQ: this is the matched question text (standard or similar question)
MatchedContent string `json:"matched_content,omitempty"`
// KnowledgeDescription is the description of the knowledge document
KnowledgeDescription string `json:"knowledge_description,omitempty"`
// KnowledgeBaseID is the ID of the knowledge base this result belongs to
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
}