mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
Merge 82b791478f into ed98be5347
This commit is contained in:
commit
759a063107
7 changed files with 348 additions and 0 deletions
|
|
@ -0,0 +1,15 @@
|
|||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_ARRAY_APPEND(
|
||||
`fields`,
|
||||
'$',
|
||||
JSON_OBJECT(
|
||||
'key', 'enable_function_call',
|
||||
'label', '启用函数调用(填false关闭,默认true)',
|
||||
'type', 'boolean',
|
||||
'default', TRUE
|
||||
)
|
||||
)
|
||||
WHERE `id` = 'SYSTEM_LLM_openai'
|
||||
AND JSON_SEARCH(
|
||||
`fields`, 'one', 'enable_function_call', NULL, '$[*].key'
|
||||
) IS NULL;
|
||||
|
|
@ -739,3 +739,10 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202608131030.sql
|
||||
- changeSet:
|
||||
id: 202608311000
|
||||
author: Codex
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202608311000.sql
|
||||
|
|
|
|||
|
|
@ -612,6 +612,7 @@ VAD:
|
|||
LLM:
|
||||
# 所有openai类型均可以修改超参,以AliLLM为例
|
||||
# 当前支持的type为openai、dify、ollama,可自行适配
|
||||
# OpenAI兼容模型不支持原生function call时,需设置enable_function_call: false,避免tools影响角色提示词
|
||||
AliLLM:
|
||||
# 定义LLM API类型
|
||||
type: openai
|
||||
|
|
@ -712,6 +713,7 @@ LLM:
|
|||
model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载
|
||||
url: http://localhost:1234/v1 # LM Studio服务地址
|
||||
api_key: lm-studio # LM Studio服务的固定API Key
|
||||
enable_function_call: false
|
||||
HomeAssistant:
|
||||
# 定义LLM API类型
|
||||
type: homeassistant
|
||||
|
|
|
|||
|
|
@ -1001,6 +1001,15 @@ class ConnectionHandler:
|
|||
self.intent_type = self.config["Intent"][
|
||||
self.config["selected_module"]["Intent"]
|
||||
]["type"]
|
||||
function_call_enabled = getattr(self.llm, "enable_function_call", True)
|
||||
if self.intent_type == "function_call" and str(
|
||||
function_call_enabled
|
||||
).strip().lower() in ("false", "0", "no", "off"):
|
||||
self.logger.bind(tag=TAG).warning(
|
||||
"当前LLM已禁用 function call,意图识别将回退为 nointent"
|
||||
)
|
||||
self.intent_type = "nointent"
|
||||
return
|
||||
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
|
||||
self.load_function_plugin = True
|
||||
"""初始化意图识别模块"""
|
||||
|
|
|
|||
|
|
@ -27,6 +27,10 @@ class LLMProvider(LLMProviderBase):
|
|||
self.base_url = config.get("base_url")
|
||||
else:
|
||||
self.base_url = config.get("url")
|
||||
self.enable_function_call = (
|
||||
str(config.get("enable_function_call", True)).strip().lower()
|
||||
not in ("false", "0", "no", "off")
|
||||
)
|
||||
|
||||
timeout_config = config.get("timeout")
|
||||
if isinstance(timeout_config, dict):
|
||||
|
|
@ -136,6 +140,20 @@ class LLMProvider(LLMProviderBase):
|
|||
responses.close()
|
||||
|
||||
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
||||
if not self.enable_function_call:
|
||||
logger.bind(tag=TAG).warning(
|
||||
"当前模型已禁用 function call,回退为纯文本流式输出"
|
||||
)
|
||||
response_stream = self.response(session_id, dialogue, **kwargs)
|
||||
try:
|
||||
for token in response_stream:
|
||||
yield token, None
|
||||
finally:
|
||||
close = getattr(response_stream, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
return
|
||||
|
||||
dialogue = self.normalize_dialogue(dialogue)
|
||||
|
||||
request_params = {
|
||||
|
|
|
|||
156
main/xiaozhi-server/tests/test_connection_function_call.py
Normal file
156
main/xiaozhi-server/tests/test_connection_function_call.py
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def stub_module(name, **attributes):
|
||||
module = ModuleType(name)
|
||||
vars(module).update(attributes)
|
||||
return module
|
||||
|
||||
|
||||
def noop(*args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
def dependency_stubs():
|
||||
error = type("StubError", (Exception,), {})
|
||||
return {
|
||||
"websockets": stub_module(
|
||||
"websockets", ServerConnection=type("ServerConnection", (), {})
|
||||
),
|
||||
"opuslib_next": stub_module("opuslib_next"),
|
||||
"numpy": stub_module("numpy"),
|
||||
"core.utils.util": stub_module(
|
||||
"core.utils.util",
|
||||
extract_json_from_string=noop,
|
||||
check_vad_update=noop,
|
||||
check_asr_update=noop,
|
||||
filter_sensitive_info=noop,
|
||||
get_system_error_response=noop,
|
||||
),
|
||||
"core.utils.modules_initialize": stub_module(
|
||||
"core.utils.modules_initialize",
|
||||
initialize_modules=noop,
|
||||
initialize_tts=noop,
|
||||
initialize_asr=noop,
|
||||
),
|
||||
"core.handle.reportHandle": stub_module(
|
||||
"core.handle.reportHandle", report=noop, enqueue_tool_report=noop
|
||||
),
|
||||
"core.providers.tts.default": stub_module(
|
||||
"core.providers.tts.default", DefaultTTS=object
|
||||
),
|
||||
"core.handle.textHandle": stub_module(
|
||||
"core.handle.textHandle", handleTextMessage=noop
|
||||
),
|
||||
"core.providers.tools.unified_tool_handler": stub_module(
|
||||
"core.providers.tools.unified_tool_handler", UnifiedToolHandler=object
|
||||
),
|
||||
"plugins_func.loadplugins": stub_module(
|
||||
"plugins_func.loadplugins", auto_import_modules=noop
|
||||
),
|
||||
"plugins_func.register": stub_module(
|
||||
"plugins_func.register",
|
||||
Action=SimpleNamespace(ERROR=-1),
|
||||
ActionResponse=object,
|
||||
all_function_registry={},
|
||||
module_func_map={},
|
||||
),
|
||||
"core.auth": stub_module("core.auth", AuthenticationError=error),
|
||||
"config.config_loader": stub_module(
|
||||
"config.config_loader", get_private_config_from_api=noop
|
||||
),
|
||||
"config.logger": stub_module(
|
||||
"config.logger",
|
||||
setup_logging=noop,
|
||||
build_module_string=noop,
|
||||
create_connection_logger=noop,
|
||||
),
|
||||
"config.manage_api_client": stub_module(
|
||||
"config.manage_api_client",
|
||||
DeviceNotFoundException=error,
|
||||
DeviceBindException=error,
|
||||
generate_and_save_chat_title=noop,
|
||||
),
|
||||
"core.utils.prompt_manager": stub_module(
|
||||
"core.utils.prompt_manager", PromptManager=object
|
||||
),
|
||||
"core.utils.voiceprint_provider": stub_module(
|
||||
"core.utils.voiceprint_provider", VoiceprintProvider=object
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
server_root = Path(__file__).parents[1]
|
||||
target = server_root / "core/connection.py"
|
||||
spec = importlib.util.spec_from_file_location("connection_under_test", target)
|
||||
connection_module = importlib.util.module_from_spec(spec)
|
||||
sys.path.insert(0, str(server_root))
|
||||
try:
|
||||
with patch.dict(sys.modules, dependency_stubs()):
|
||||
spec.loader.exec_module(connection_module)
|
||||
finally:
|
||||
sys.path.remove(str(server_root))
|
||||
|
||||
|
||||
class NullLogger:
|
||||
def bind(self, **kwargs):
|
||||
return self
|
||||
|
||||
def warning(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class ConnectionFunctionCallTest(unittest.TestCase):
|
||||
def make_connection(self, llm):
|
||||
connection = connection_module.ConnectionHandler.__new__(
|
||||
connection_module.ConnectionHandler
|
||||
)
|
||||
connection.intent = object()
|
||||
connection.config = {
|
||||
"selected_module": {"Intent": "test_intent"},
|
||||
"Intent": {"test_intent": {"type": "function_call"}},
|
||||
}
|
||||
connection.llm = llm
|
||||
connection.logger = NullLogger()
|
||||
connection.load_function_plugin = False
|
||||
connection.func_handler = None
|
||||
connection.loop = None
|
||||
connection.dialogue = connection_module.Dialogue()
|
||||
return connection
|
||||
|
||||
def test_disabled_function_call_skips_tools_and_fewshot(self):
|
||||
for value in (False, "false"):
|
||||
with self.subTest(value=value):
|
||||
connection = self.make_connection(
|
||||
SimpleNamespace(enable_function_call=value)
|
||||
)
|
||||
|
||||
with patch.object(connection_module, "UnifiedToolHandler") as handler:
|
||||
connection._initialize_intent()
|
||||
connection._inject_tool_call_fewshot()
|
||||
|
||||
self.assertEqual(connection.intent_type, "nointent")
|
||||
self.assertFalse(connection.load_function_plugin)
|
||||
self.assertIsNone(connection.func_handler)
|
||||
self.assertEqual(connection.dialogue.dialogue, [])
|
||||
handler.assert_not_called()
|
||||
|
||||
def test_function_call_remains_enabled_by_default(self):
|
||||
connection = self.make_connection(SimpleNamespace())
|
||||
|
||||
with patch.object(connection_module, "UnifiedToolHandler") as handler:
|
||||
connection._initialize_intent()
|
||||
|
||||
self.assertEqual(connection.intent_type, "function_call")
|
||||
self.assertTrue(connection.load_function_plugin)
|
||||
self.assertIs(connection.func_handler, handler.return_value)
|
||||
handler.assert_called_once_with(connection)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
141
main/xiaozhi-server/tests/test_openai_provider.py
Normal file
141
main/xiaozhi-server/tests/test_openai_provider.py
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import patch, sentinel
|
||||
|
||||
|
||||
class NullLogger:
|
||||
def bind(self, **kwargs):
|
||||
return self
|
||||
|
||||
def debug(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
info = debug
|
||||
error = debug
|
||||
warning = debug
|
||||
|
||||
|
||||
def stub_module(name, **attributes):
|
||||
module = ModuleType(name)
|
||||
vars(module).update(attributes)
|
||||
return module
|
||||
|
||||
|
||||
stubs = {
|
||||
"httpx": stub_module("httpx", Timeout=lambda *args, **kwargs: None),
|
||||
"openai": stub_module("openai", OpenAI=None),
|
||||
"openai.types": stub_module(
|
||||
"openai.types", CompletionUsage=type("Usage", (), {})
|
||||
),
|
||||
"config.logger": stub_module("config.logger", setup_logging=lambda: NullLogger()),
|
||||
"core.utils.util": stub_module("core.utils.util", check_model_key=lambda *args: None),
|
||||
"core.providers.llm.base": stub_module(
|
||||
"core.providers.llm.base", LLMProviderBase=object
|
||||
),
|
||||
}
|
||||
target = Path(__file__).parents[1] / "core/providers/llm/openai/openai.py"
|
||||
spec = importlib.util.spec_from_file_location("openai_provider_under_test", target)
|
||||
provider_module = importlib.util.module_from_spec(spec)
|
||||
with patch.dict(sys.modules, stubs):
|
||||
spec.loader.exec_module(provider_module)
|
||||
|
||||
|
||||
class FakeStream:
|
||||
def __init__(self):
|
||||
delta = SimpleNamespace(content="角色化回复", tool_calls=None)
|
||||
self.chunks = [SimpleNamespace(choices=[SimpleNamespace(delta=delta)])]
|
||||
self.closed = False
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.chunks)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeCompletions:
|
||||
def __init__(self):
|
||||
self.stream = FakeStream()
|
||||
self.request = None
|
||||
|
||||
def create(self, **kwargs):
|
||||
self.request = kwargs
|
||||
return self.stream
|
||||
|
||||
|
||||
class ClosableTokens:
|
||||
def __init__(self, tokens):
|
||||
self.tokens = tokens
|
||||
self.closed = False
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.tokens)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class OpenAIProviderTest(unittest.TestCase):
|
||||
def make_provider(self, enable_function_call=sentinel.missing):
|
||||
completions = FakeCompletions()
|
||||
client = SimpleNamespace(chat=SimpleNamespace(completions=completions))
|
||||
provider_module.openai.OpenAI = lambda **kwargs: client
|
||||
config = {
|
||||
"model_name": "test-model",
|
||||
"api_key": "test-key",
|
||||
"base_url": "http://localhost/v1",
|
||||
}
|
||||
if enable_function_call is not sentinel.missing:
|
||||
config["enable_function_call"] = enable_function_call
|
||||
return provider_module.LLMProvider(config), completions
|
||||
|
||||
def test_default_true_and_blank_forward_tools(self):
|
||||
tools = [{"type": "function", "function": {"name": "get_time"}}]
|
||||
dialogue = [{"role": "system", "content": "你是湾湾小何"}]
|
||||
|
||||
for value in (sentinel.missing, True, ""):
|
||||
with self.subTest(value=value):
|
||||
provider, completions = self.make_provider(value)
|
||||
result = list(provider.response_with_functions("sid", dialogue, tools))
|
||||
|
||||
self.assertIs(completions.request["tools"], tools)
|
||||
self.assertIs(completions.request["messages"], dialogue)
|
||||
self.assertEqual(result, [("角色化回复", None)])
|
||||
self.assertTrue(completions.stream.closed)
|
||||
|
||||
def test_disabled_function_call_closes_delegated_stream_on_early_stop(self):
|
||||
provider, _ = self.make_provider(False)
|
||||
delegated_stream = ClosableTokens(["第一段", "第二段"])
|
||||
|
||||
with patch.object(provider, "response", return_value=delegated_stream):
|
||||
responses = provider.response_with_functions("sid", [])
|
||||
self.assertEqual(next(responses), ("第一段", None))
|
||||
responses.close()
|
||||
|
||||
self.assertTrue(delegated_stream.closed)
|
||||
|
||||
def test_function_call_disabled_uses_regular_response_as_tuples(self):
|
||||
dialogue = [{"role": "system", "content": "你是湾湾小何"}]
|
||||
|
||||
for value in (False, "false"):
|
||||
with self.subTest(value=value):
|
||||
provider, completions = self.make_provider(value)
|
||||
with patch.object(provider, "response", wraps=provider.response) as response:
|
||||
result = list(
|
||||
provider.response_with_functions(
|
||||
"sid", dialogue, [{}], max_tokens=42, temperature=0.3
|
||||
)
|
||||
)
|
||||
|
||||
response.assert_called_once_with(
|
||||
"sid", dialogue, max_tokens=42, temperature=0.3
|
||||
)
|
||||
self.assertNotIn("tools", completions.request)
|
||||
self.assertIs(completions.request["messages"], dialogue)
|
||||
self.assertEqual(completions.request["max_tokens"], 42)
|
||||
self.assertEqual(completions.request["temperature"], 0.3)
|
||||
self.assertEqual(result, [("角色化回复", None)])
|
||||
self.assertTrue(completions.stream.closed)
|
||||
Loading…
Reference in a new issue