清理意图识别模块

This commit is contained in:
玄凤科技 2025-04-17 23:15:03 +08:00
parent 541f2de599
commit 52e54daa2b
16 changed files with 74 additions and 544 deletions

View file

@ -44,7 +44,7 @@ class TTSException(RuntimeError):
class ConnectionHandler: class ConnectionHandler:
def __init__( def __init__(
self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory
): ):
self.config = copy.deepcopy(config) self.config = copy.deepcopy(config)
self.logger = setup_logging() self.logger = setup_logging()
@ -78,7 +78,6 @@ class ConnectionHandler:
self.llm = _llm self.llm = _llm
self.tts = _tts self.tts = _tts
self.memory = _memory self.memory = _memory
self.intent = _intent
# vad相关变量 # vad相关变量
self.client_audio_buffer = bytearray() self.client_audio_buffer = bytearray()
@ -111,6 +110,7 @@ class ConnectionHandler:
self.close_after_chat = False # 是否在聊天结束后关闭连接 self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = False self.use_function_call_mode = False
self.use_function_call_by_prompt = False
async def handle_connection(self, ws): async def handle_connection(self, ws):
try: try:
@ -209,8 +209,10 @@ class ConnectionHandler:
"""加载记忆""" """加载记忆"""
self._initialize_memory() self._initialize_memory()
"""加载意图识别""" """加载意图识别"""
self._initialize_intent() self._initialize_intent()
"""加载位置信息""" """加载位置信息"""
self.client_ip_info = get_ip_info(self.client_ip, self.logger) self.client_ip_info = get_ip_info(self.client_ip, self.logger)
if self.client_ip_info is not None and "city" in self.client_ip_info: if self.client_ip_info is not None and "city" in self.client_ip_info:
@ -311,8 +313,6 @@ class ConnectionHandler:
self.tts = modules["tts"] self.tts = modules["tts"]
if modules.get("llm", None) is not None: if modules.get("llm", None) is not None:
self.llm = modules["llm"] self.llm = modules["llm"]
if modules.get("intent", None) is not None:
self.intent = modules["intent"]
if modules.get("memory", None) is not None: if modules.get("memory", None) is not None:
self.memory = modules["memory"] self.memory = modules["memory"]
if modules.get("prompt", None) is not None: if modules.get("prompt", None) is not None:
@ -324,44 +324,13 @@ class ConnectionHandler:
self.memory.init_memory(device_id, self.llm) self.memory.init_memory(device_id, self.llm)
def _initialize_intent(self): def _initialize_intent(self):
if ( intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]]["type"]
self.config["Intent"][self.config["selected_module"]["Intent"]]["type"] if (intent_type == "function_call"):
== "function_call"
):
self.use_function_call_mode = True self.use_function_call_mode = True
"""初始化意图识别模块""" elif (intent_type == "intent_llm"):
# 获取意图识别配置 self.use_function_call_by_prompt = True
intent_config = self.config["Intent"] else:
intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
"type"
]
# 如果使用 nointent,直接返回
if intent_type == "nointent":
return return
# 使用 intent_llm 模式
elif intent_type == "intent_llm":
intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
"llm"
]
if intent_llm_name and intent_llm_name in self.config["LLM"]:
# 如果配置了专用LLM,则创建独立的LLM实例
from core.utils import llm as llm_utils
intent_llm_config = self.config["LLM"][intent_llm_name]
intent_llm_type = intent_llm_config.get("type", intent_llm_name)
intent_llm = llm_utils.create_instance(
intent_llm_type, intent_llm_config
)
self.logger.bind(tag=TAG).info(
f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}"
)
self.intent.set_llm(intent_llm)
else:
# 否则使用主LLM
self.intent.set_llm(self.llm)
self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
"""加载插件""" """加载插件"""
self.func_handler = FunctionHandler(self) self.func_handler = FunctionHandler(self)
@ -453,7 +422,11 @@ class ConnectionHandler:
) )
return True return True
def chat_with_function_calling(self, query, tool_call=False): # 处理函数调用的结果
# query: 用户输入的查询
# tool_call: 是否是工具调用
# use_system_prompt: 是否使用系统提示词,原则上只有不支持function calling的模型才会使用
def chat_with_function_calling(self, query, tool_call=False, use_system_prompt=False):
self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
"""Chat with function calling for intent detection using streaming""" """Chat with function calling for intent detection using streaming"""
@ -483,6 +456,7 @@ class ConnectionHandler:
self.session_id, self.session_id,
self.dialogue.get_llm_dialogue_with_memory(memory_str), self.dialogue.get_llm_dialogue_with_memory(memory_str),
functions=functions, functions=functions,
use_system_prompt=use_system_prompt,
) )
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
@ -601,7 +575,7 @@ class ConnectionHandler:
result = self.func_handler.handle_llm_function_call( result = self.func_handler.handle_llm_function_call(
self, function_call_data self, function_call_data
) )
self._handle_function_result(result, function_call_data, text_index + 1) self._handle_function_result(result, function_call_data, text_index + 1, use_system_prompt)
# 处理最后剩余的文本 # 处理最后剩余的文本
full_text = "".join(response_message) full_text = "".join(response_message)
@ -671,7 +645,7 @@ class ConnectionHandler:
return ActionResponse(action=Action.REQLLM, result="工具调用出错", response="") return ActionResponse(action=Action.REQLLM, result="工具调用出错", response="")
def _handle_function_result(self, result, function_call_data, text_index): def _handle_function_result(self, result, function_call_data, text_index, use_system_prompt):
if result.action == Action.RESPONSE: # 直接回复前端 if result.action == Action.RESPONSE: # 直接回复前端
text = result.response text = result.response
self.recode_first_last_text(text, text_index) self.recode_first_last_text(text, text_index)
@ -705,7 +679,7 @@ class ConnectionHandler:
self.dialogue.put( self.dialogue.put(
Message(role="tool", tool_call_id=function_id, content=text) Message(role="tool", tool_call_id=function_id, content=text)
) )
self.chat_with_function_calling(text, tool_call=True) self.chat_with_function_calling(text, tool_call=True, use_system_prompt=use_system_prompt)
elif result.action == Action.NOTFOUND: elif result.action == Action.NOTFOUND:
text = result.result text = result.result
self.recode_first_last_text(text, text_index) self.recode_first_last_text(text, text_index)

View file

@ -1,150 +0,0 @@
from config.logger import setup_logging
import json
import uuid
from core.handle.sendAudioHandle import send_stt_message
from core.handle.helloHandle import checkWakeupWords
from core.utils.util import remove_punctuation_and_length
from core.utils.dialogue import Message
from loguru import logger
TAG = __name__
logger = setup_logging()
async def handle_user_intent(conn, text):
# 检查是否有明确的退出命令
if await check_direct_exit(conn, text):
return True
# 检查是否是唤醒词
if await checkWakeupWords(conn, text):
return True
if conn.use_function_call_mode:
# 使用支持function calling的聊天方法,不再进行意图分析
return False
# 使用LLM进行意图分析
intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result:
return False
# 处理各种意图
return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令"""
_, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
await send_stt_message(conn, text)
await conn.close()
return True
return False
async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图"""
if not hasattr(conn, "intent") or not conn.intent:
logger.bind(tag=TAG).warning("意图识别服务未初始化")
return None
# 对话历史记录
dialogue = conn.dialogue
try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result
except Exception as e:
logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
return None
async def process_intent_result(conn, intent_result, original_text):
"""处理意图识别结果"""
try:
# 尝试将结果解析为JSON
intent_data = json.loads(intent_result)
# 检查是否有function_call
if "function_call" in intent_data:
# 直接从意图识别获取了function_call
logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
)
function_name = intent_data["function_call"]["name"]
if function_name == "continue_chat":
return False
if function_name == "play_music":
funcItem = conn.func_handler.get_function(function_name)
if not funcItem:
conn.func_handler.function_registry.register_function("play_music")
function_args = None
if "arguments" in intent_data["function_call"]:
function_args = intent_data["function_call"]["arguments"]
# 确保参数是字符串格式的JSON
if isinstance(function_args, dict):
function_args = json.dumps(function_args)
function_call_data = {
"name": function_name,
"id": str(uuid.uuid4().hex),
"arguments": function_args,
}
await send_stt_message(conn, original_text)
# 使用executor执行函数调用和结果处理
def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text))
result = conn.func_handler.handle_llm_function_call(
conn, function_call_data
)
if result and function_name != "play_music":
# 获取当前最新的文本索引
text = result.response
if text is None:
text = result.result
if text is not None:
text_index = (
conn.tts_last_text_index + 1
if hasattr(conn, "tts_last_text_index")
else 0
)
conn.recode_first_last_text(text, text_index)
future = conn.executor.submit(
conn.speak_and_play, text, text_index
)
conn.llm_finish_task = True
conn.tts_queue.put(future)
conn.dialogue.put(Message(role="assistant", content=text))
# 将函数执行放在线程池中
conn.executor.submit(process_function_call)
return True
return False
except json.JSONDecodeError as e:
logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
return False
def extract_text_in_brackets(s):
"""
从字符串中提取中括号内的文字
:param s: 输入字符串
:return: 中括号内的文字,如果不存在则返回空字符串
"""
left_bracket_index = s.find("[")
right_bracket_index = s.find("]")
if (
left_bracket_index != -1
and right_bracket_index != -1
and left_bracket_index < right_bracket_index
):
return s[left_bracket_index + 1 : right_bracket_index]
else:
return ""

View file

@ -3,7 +3,7 @@ import time
import asyncio import asyncio
from core.utils.util import remove_punctuation_and_length from core.utils.util import remove_punctuation_and_length
from core.handle.sendAudioHandle import send_stt_message from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent from core.handle.helloHandle import checkWakeupWords
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -47,6 +47,29 @@ async def handleAudioMessage(conn, audio):
conn.reset_vad_states() conn.reset_vad_states()
async def handle_user_intent(conn, text):
# 检查是否有明确的退出命令
if await check_direct_exit(conn, text):
return True
# 检查是否是唤醒词
if await checkWakeupWords(conn, text):
return True
return False
async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令"""
_, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
await send_stt_message(conn, text)
await conn.close()
return True
return False
async def startToChat(conn, text): async def startToChat(conn, text):
if conn.need_bind: if conn.need_bind:
await check_bind_device(conn) await check_bind_device(conn)
@ -64,6 +87,8 @@ async def startToChat(conn, text):
if conn.use_function_call_mode: if conn.use_function_call_mode:
# 使用支持function calling的聊天方法 # 使用支持function calling的聊天方法
conn.executor.submit(conn.chat_with_function_calling, text) conn.executor.submit(conn.chat_with_function_calling, text)
elif conn.use_function_call_by_prompt:
conn.executor.submit(conn.chat_with_function_calling, text, False, True)
else: else:
conn.executor.submit(conn.chat, text) conn.executor.submit(conn.chat, text)

View file

@ -1,45 +0,0 @@
from abc import ABC, abstractmethod
from typing import List, Dict
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class IntentProviderBase(ABC):
def __init__(self, config):
self.config = config
self.intent_options = [
{
"name": "handle_exit_intent",
"desc": "结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候",
},
{
"name": "play_music",
"desc": "播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图",
},
{"name": "get_time", "desc": "获取今天日期或者当前时间信息"},
{"name": "continue_chat", "desc": "继续聊天"},
]
def set_llm(self, llm):
self.llm = llm
# 获取模型名称和类型信息
model_name = getattr(llm, "model_name", str(llm.__class__.__name__))
# 记录更详细的日志
logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}")
@abstractmethod
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
检测用户最后一句话的意图
Args:
dialogue_history: 对话历史记录列表,每条记录包含role和content
Returns:
返回识别出的意图,格式为:
- "继续聊天"
- "结束聊天"
- "播放音乐 歌名" 或 "随机播放音乐"
- "查询天气 地点名" 或 "查询天气 [当前位置]"
"""
pass

View file

@ -1,22 +0,0 @@
from ..base import IntentProviderBase
from typing import List, Dict
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Args:
dialogue_history: 对话历史记录列表
text: 本次对话记录
Returns:
固定返回"继续聊天"
"""
logger.bind(tag=TAG).debug(
"Using functionCallProvider, always returning continue chat"
)
return '{"function_call": {"name": "continue_chat"}}'

View file

@ -1,217 +0,0 @@
from typing import List, Dict
from ..base import IntentProviderBase
from plugins_func.functions.play_music import initialize_music_handler
from config.logger import setup_logging
import re
import json
import hashlib
import time
TAG = __name__
logger = setup_logging()
class IntentProvider(IntentProviderBase):
def __init__(self, config):
super().__init__(config)
self.llm = None
self.promot = self.get_intent_system_prompt()
# 添加缓存管理
self.intent_cache = {} # 缓存意图识别结果
self.cache_expiry = 600 # 缓存有效期10分钟
self.cache_max_size = 100 # 最多缓存100个意图
def get_intent_system_prompt(self) -> str:
"""
根据配置的意图选项动态生成系统提示词
Returns:
格式化后的系统提示词
"""
prompt = (
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
"<start>"
f"{str(self.intent_options)}"
"<end>\n"
"处理步骤:"
"1. 思考意图类型,生成function_call格式"
"\n\n"
"返回格式示例:\n"
'1. 播放音乐意图: {"function_call": {"name": "play_music", "arguments": {"song_name": "音乐名称"}}}\n'
'2. 结束对话意图: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
'3. 获取当天日期时间: {"function_call": {"name": "get_time"}}\n'
'4. 继续聊天意图: {"function_call": {"name": "continue_chat"}}\n'
"\n"
"注意:\n"
'- 播放音乐:无歌名时,song_name设为"random"\n'
"- 如果没有明显的意图,应按照继续聊天意图处理\n"
"- 只返回纯JSON,不要任何其他内容\n"
"\n"
"示例分析:\n"
"```\n"
"用户: 你也太搞笑了\n"
'返回: {"function_call": {"name": "continue_chat"}}\n'
"```\n"
"```\n"
"用户: 现在是几号了?现在几点了?\n"
'返回: {"function_call": {"name": "get_time"}}\n'
"```\n"
"```\n"
"用户: 我们明天再聊吧\n"
'返回: {"function_call": {"name": "handle_exit_intent"}}\n'
"```\n"
"```\n"
"用户: 播放中秋月\n"
'返回: {"function_call": {"name": "play_music", "arguments": {"song_name": "中秋月"}}}\n'
"```\n"
"```\n"
"可用的音乐名称:\n"
)
return prompt
def clean_cache(self):
"""清理过期缓存"""
now = time.time()
# 找出过期键
expired_keys = [
k
for k, v in self.intent_cache.items()
if now - v["timestamp"] > self.cache_expiry
]
for key in expired_keys:
del self.intent_cache[key]
# 如果缓存太大,移除最旧的条目
if len(self.intent_cache) > self.cache_max_size:
# 按时间戳排序并保留最新的条目
sorted_items = sorted(
self.intent_cache.items(), key=lambda x: x[1]["timestamp"]
)
for key, _ in sorted_items[: len(sorted_items) - self.cache_max_size]:
del self.intent_cache[key]
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
if not self.llm:
raise ValueError("LLM provider not set")
# 记录整体开始时间
total_start_time = time.time()
# 打印使用的模型信息
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}")
# 计算缓存键
cache_key = hashlib.md5(text.encode()).hexdigest()
# 检查缓存
if cache_key in self.intent_cache:
cache_entry = self.intent_cache[cache_key]
# 检查缓存是否过期
if time.time() - cache_entry["timestamp"] <= self.cache_expiry:
cache_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"使用缓存的意图: {cache_key} -> {cache_entry['intent']}, 耗时: {cache_time:.4f}秒"
)
return cache_entry["intent"]
# 清理缓存
self.clean_cache()
# 构建用户最后一句话的提示
msgStr = ""
# 只使用最后两句即可
if len(dialogue_history) >= 2:
# 保证最少有两句话的时候处理
msgStr += f"{dialogue_history[-2].role}: {dialogue_history[-2].content}\n"
msgStr += f"{dialogue_history[-1].role}: {dialogue_history[-1].content}\n"
msgStr += f"User: {text}\n"
user_prompt = f"当前的对话如下:\n{msgStr}"
music_config = initialize_music_handler(conn)
music_file_names = music_config["music_file_names"]
prompt_music = f"{self.promot}\n<start>{music_file_names}\n<end>"
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 记录预处理完成时间
preprocess_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒")
# 使用LLM进行意图识别
llm_start_time = time.time()
logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
intent = self.llm.response_no_stream(
system_prompt=prompt_music, user_prompt=user_prompt
)
# 记录LLM调用完成时间
llm_time = time.time() - llm_start_time
logger.bind(tag=TAG).debug(
f"LLM意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒"
)
# 记录后处理开始时间
postprocess_start_time = time.time()
# 清理和解析响应
intent = intent.strip()
# 尝试提取JSON部分
match = re.search(r"\{.*\}", intent, re.DOTALL)
if match:
intent = match.group(0)
# 记录总处理时间
total_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'"
)
# 尝试解析为JSON
try:
intent_data = json.loads(intent)
# 如果包含function_call,则格式化为适合处理的格式
if "function_call" in intent_data:
function_data = intent_data["function_call"]
function_name = function_data.get("name")
function_args = function_data.get("arguments", {})
# 记录识别到的function call
logger.bind(tag=TAG).info(
f"识别到function call: {function_name}, 参数: {function_args}"
)
# 添加到缓存
self.intent_cache[cache_key] = {
"intent": intent,
"timestamp": time.time(),
}
# 后处理时间
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
# 确保返回完全序列化的JSON字符串
return intent
else:
# 添加到缓存
self.intent_cache[cache_key] = {
"intent": intent,
"timestamp": time.time(),
}
# 后处理时间
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
# 返回普通意图
return intent
except json.JSONDecodeError:
# 后处理时间
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).error(
f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒"
)
# 如果解析失败,默认返回继续聊天意图
return '{"intent": "继续聊天"}'

View file

@ -1,22 +0,0 @@
from ..base import IntentProviderBase
from typing import List, Dict
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Args:
dialogue_history: 对话历史记录列表
text: 本次对话记录
Returns:
固定返回"继续聊天"
"""
logger.bind(tag=TAG).debug(
"Using NoIntentProvider, always returning continue chat"
)
return '{"function_call": {"name": "continue_chat"}}'

View file

@ -26,7 +26,7 @@ class LLMProviderBase(ABC):
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
return "【LLM服务响应异常】" return "【LLM服务响应异常】"
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
""" """
Default implementation for function calling (streaming) Default implementation for function calling (streaming)
This should be overridden by providers that support function calls This should be overridden by providers that support function calls

View file

@ -48,7 +48,7 @@ class LLMProvider(LLMProviderBase):
print(event.message.content, end="", flush=True) print(event.message.content, end="", flush=True)
yield event.message.content yield event.message.content
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
if len(dialogue) == 2 and functions is not None and len(functions) > 0: if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词 # 第一次调用llm, 取最后一条用户消息,附加tool提示词
last_msg = dialogue[-1]["content"] last_msg = dialogue[-1]["content"]

View file

@ -83,7 +83,7 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(f"Error in response generation: {e}") logger.bind(tag=TAG).error(f"Error in response generation: {e}")
yield "【服务响应异常】" yield "【服务响应异常】"
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
if len(dialogue) == 2 and functions is not None and len(functions) > 0: if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词 # 第一次调用llm, 取最后一条用户消息,附加tool提示词
last_msg = dialogue[-1]["content"] last_msg = dialogue[-1]["content"]

View file

@ -49,7 +49,7 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
yield "【Ollama服务响应异常】" yield "【Ollama服务响应异常】"
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
try: try:
stream = self.client.chat.completions.create( stream = self.client.chat.completions.create(
model=self.model_name, model=self.model_name,

View file

@ -2,6 +2,8 @@ import openai
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase from core.providers.llm.base import LLMProviderBase
from core.providers.llm.system_prompt import get_system_prompt_for_function
import json
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -63,11 +65,29 @@ class LLMProvider(LLMProviderBase):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}") logger.bind(tag=TAG).error(f"Error in response generation: {e}")
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
try: try:
stream = self.client.chat.completions.create( if not use_system_prompt:
model=self.model_name, messages=dialogue, stream=True, tools=functions stream = self.client.chat.completions.create(
) model=self.model_name, messages=dialogue, stream=True, tools=functions
)
else:
print(dialogue)
# 使用系统提示词, 需要将functions添加到对话中
system_prompt = dialogue[0]["content"]
if system_prompt == None :
system_prompt = ""
# 将functions转换为字符串格式
function_str = json.dumps(functions, ensure_ascii=False)
print (f"system_prompt: {system_prompt}..")
modify_msg = get_system_prompt_for_function(function_str) + system_prompt
dialogue[0]["content"] = modify_msg
stream = self.client.chat.completions.create(
model=self.model_name, messages=dialogue, stream=True
)
for chunk in stream: for chunk in stream:
yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls

View file

@ -57,7 +57,7 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}") logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}")
yield "【Xinference服务响应异常】" yield "【Xinference服务响应异常】"
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False):
try: try:
logger.bind(tag=TAG).debug(f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}") logger.bind(tag=TAG).debug(f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}")
if functions: if functions:

View file

@ -1,17 +0,0 @@
import os
import sys
from config.logger import setup_logging
import importlib
logger = setup_logging()
def create_instance(class_name, *args, **kwargs):
# 创建intent实例
if os.path.exists(os.path.join('core', 'providers', 'intent', class_name, f'{class_name}.py')):
lib_name = f'core.providers.intent.{class_name}.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].IntentProvider(*args, **kwargs)
raise ValueError(f"不支持的intent类型: {class_name},请检查该配置的type是否设置正确")

View file

@ -4,7 +4,7 @@ import subprocess
import re import re
import requests import requests
from typing import Dict, Any from typing import Dict, Any
from core.utils import tts, llm, intent, memory, vad, asr from core.utils import tts, llm, memory, vad, asr
TAG = __name__ TAG = __name__
@ -267,20 +267,6 @@ def initialize_modules(
) )
logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}") logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}")
# 初始化Intent模块
if init_intent:
select_intent_module = config["selected_module"]["Intent"]
intent_type = (
select_intent_module
if "type" not in config["Intent"][select_intent_module]
else config["Intent"][select_intent_module]["type"]
)
modules["intent"] = intent.create_instance(
intent_type,
config["Intent"][select_intent_module],
)
logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}")
# 初始化Memory模块 # 初始化Memory模块
if init_memory: if init_memory:
select_memory_module = config["selected_module"]["Memory"] select_memory_module = config["selected_module"]["Memory"]

View file

@ -18,7 +18,6 @@ class WebSocketServer:
self._asr = modules["asr"] self._asr = modules["asr"]
self._tts = modules["tts"] self._tts = modules["tts"]
self._llm = modules["llm"] self._llm = modules["llm"]
self._intent = modules["intent"]
self._memory = modules["memory"] self._memory = modules["memory"]
self.active_connections = set() self.active_connections = set()
@ -52,7 +51,6 @@ class WebSocketServer:
self._llm, self._llm,
self._tts, self._tts,
self._memory, self._memory,
self._intent,
) )
self.active_connections.add(handler) self.active_connections.add(handler)
try: try: