update:优化提示词

This commit is contained in:
hrz
2025-07-11 10:15:14 +08:00
parent cd58b3a39a
commit 108c87f395
5 changed files with 39 additions and 64 deletions
+8 -33
View File
@@ -645,37 +645,8 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
self.llm_finish_task = False
# 检查是否是JSON格式的消息(包含说话人信息)
enhanced_query = query
try:
if query.strip().startswith("{") and query.strip().endswith("}"):
data = json.loads(query)
if "speaker" in data and "content" in data:
# 直接使用JSON格式,不重新格式化
enhanced_query = query
self.logger.bind(tag=TAG).info(f"识别到说话人: {data['speaker']}")
else:
# 如果有说话人信息但不是JSON格式,按原逻辑处理
if hasattr(self, "current_speaker") and self.current_speaker:
enhanced_query = f"[说话人: {self.current_speaker}] {query}"
self.logger.bind(tag=TAG).info(
f"识别到说话人: {self.current_speaker}"
)
else:
# 如果有说话人信息但不是JSON格式,按原逻辑处理
if hasattr(self, "current_speaker") and self.current_speaker:
enhanced_query = f"[说话人: {self.current_speaker}] {query}"
self.logger.bind(tag=TAG).info(
f"识别到说话人: {self.current_speaker}"
)
except json.JSONDecodeError:
# JSON解析失败,按原逻辑处理
if hasattr(self, "current_speaker") and self.current_speaker:
enhanced_query = f"[说话人: {self.current_speaker}] {query}"
self.logger.bind(tag=TAG).info(f"识别到说话人: {self.current_speaker}")
if not tool_call:
self.dialogue.put(Message(role="user", content=enhanced_query))
self.dialogue.put(Message(role="user", content=query))
# Define intent functions
functions = None
@@ -688,7 +659,7 @@ class ConnectionHandler:
memory_str = None
if self.memory is not None:
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(enhanced_query), self.loop
self.memory.query_memory(query), self.loop
)
memory_str = future.result()
@@ -698,13 +669,17 @@ class ConnectionHandler:
# 使用支持functions的streaming接口
llm_responses = self.llm.response_with_functions(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(memory_str),
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
),
functions=functions,
)
else:
llm_responses = self.llm.response(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(memory_str),
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
),
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
+16 -18
View File
@@ -2,7 +2,6 @@ import uuid
import re
from typing import List, Dict
from datetime import datetime
from config.settings import load_config
class Message:
@@ -49,7 +48,7 @@ class Dialogue:
def get_llm_dialogue(self) -> List[Dict[str, str]]:
# 直接调用get_llm_dialogue_with_memory,传入None作为memory_str
# 这样确保说话人功能在所有调用路径下都生效
return self.get_llm_dialogue_with_memory(None)
return self.get_llm_dialogue_with_memory(None, None)
def update_system_message(self, new_content: str):
"""更新或添加系统消息"""
@@ -61,7 +60,7 @@ class Dialogue:
self.put(Message(role="system", content=new_content))
def get_llm_dialogue_with_memory(
self, memory_str: str = None
self, memory_str: str = None, voiceprint_config: dict = None
) -> List[Dict[str, str]]:
# 构建对话
dialogue = []
@@ -74,38 +73,37 @@ class Dialogue:
if system_message:
# 基础系统提示
enhanced_system_prompt = system_message.content
# 添加说话人个性化描述
try:
config = load_config()
voiceprint_config = config.get("voiceprint", {})
speakers = voiceprint_config.get("speakers", [])
if speakers:
enhanced_system_prompt += "\n\n<speaker>"
enhanced_system_prompt += "\n\n<speakers_info>"
for speaker_str in speakers:
try:
parts = speaker_str.split(",", 2)
if len(parts) >= 2:
speaker_id = parts[0].strip()
name = parts[1].strip()
# 如果描述为空,则为""
description = parts[2].strip() if len(parts) >= 3 else ""
description = (
parts[2].strip() if len(parts) >= 3 else ""
)
enhanced_system_prompt += f"\n- {name}{description}"
except:
pass
enhanced_system_prompt += "\n\n</speaker>"
enhanced_system_prompt += "\n\n</speakers_info>"
except:
# 配置读取失败时忽略错误,不影响其他功能
pass
# 使用正则表达式匹配 <memory> 标签,不管中间有什么内容
enhanced_system_prompt = re.sub(
r"<memory>.*?</memory>",
f"<memory>\n{memory_str}\n</memory>",
system_message.content,
flags=re.DOTALL,
)
if memory_str is not None:
enhanced_system_prompt = re.sub(
r"<memory>.*?</memory>",
f"<memory>\n{memory_str}\n</memory>",
enhanced_system_prompt,
flags=re.DOTALL,
)
dialogue.append({"role": "system", "content": enhanced_system_prompt})
# 添加用户和助手的对话
@@ -7,6 +7,7 @@ import os
import cnlunar
from typing import Dict, Any
from config.logger import setup_logging
from jinja2 import Template
TAG = __name__
@@ -196,7 +197,8 @@ class PromptManager:
)
# 替换模板变量
enhanced_prompt = self.base_prompt_template.format(
template = Template(self.base_prompt_template)
enhanced_prompt = template.render(
base_prompt=user_prompt,
current_time=current_time,
today_date=today_date,