mula.liu 2026-01-30 08:55:12 +08:00
commit 883a1a2f1b
2 changed files with 73 additions and 48 deletions

View File

@ -14,31 +14,19 @@ class LLMService:
# 设置dashscope API key # 设置dashscope API key
dashscope.api_key = config_module.QWEN_API_KEY dashscope.api_key = config_module.QWEN_API_KEY
@property def _get_llm_call_params(self) -> Dict[str, Any]:
def model_name(self): """
"""动态获取模型名称""" 获取 dashscope.Generation.call() 所需的参数字典
return SystemConfigService.get_llm_model_name(default="qwen-plus")
@property Returns:
def system_prompt(self): Dict: 包含 modeltimeouttemperaturetop_p 的参数字典
"""动态获取系统提示词fallback优先使用prompts表""" """
# 保留config中的system_prompt作为后备 return {
return config_module.LLM_CONFIG.get("system_prompt", "请根据提供的内容进行总结和分析。") 'model': SystemConfigService.get_llm_model_name(),
'timeout': SystemConfigService.get_llm_timeout(),
@property 'temperature': SystemConfigService.get_llm_temperature(),
def time_out(self): 'top_p': SystemConfigService.get_llm_top_p(),
"""动态获取超时时间""" }
return SystemConfigService.get_llm_timeout(default=120)
@property
def temperature(self):
"""动态获取temperature"""
return SystemConfigService.get_llm_temperature(default=0.7)
@property
def top_p(self):
"""动态获取top_p"""
return SystemConfigService.get_llm_top_p(default=0.9)
def get_task_prompt(self, task_type: str, cursor=None, prompt_id: Optional[int] = None) -> str: def get_task_prompt(self, task_type: str, cursor=None, prompt_id: Optional[int] = None) -> str:
""" """
@ -91,23 +79,21 @@ class LLMService:
def _get_default_prompt(self, task_name: str) -> str: def _get_default_prompt(self, task_name: str) -> str:
"""获取默认提示词""" """获取默认提示词"""
system_prompt = config_module.LLM_CONFIG.get("system_prompt", "请根据提供的内容进行总结和分析。")
default_prompts = { default_prompts = {
'MEETING_TASK': self.system_prompt, # 使用配置文件中的系统提示词 'MEETING_TASK': system_prompt,
'KNOWLEDGE_TASK': "请根据提供的信息生成知识库文章。", 'KNOWLEDGE_TASK': "请根据提供的信息生成知识库文章。",
} }
return default_prompts.get(task_name, "请根据提供的内容进行总结和分析。") return default_prompts.get(task_name, "请根据提供的内容进行总结和分析。")
def _call_llm_api_stream(self, prompt: str) -> Generator[str, None, None]: def _call_llm_api_stream(self, prompt: str) -> Generator[str, None, None]:
"""流式调用阿里Qwen3大模型API""" """流式调用阿里Qwen大模型API"""
try: try:
responses = dashscope.Generation.call( responses = dashscope.Generation.call(
model=self.model_name, **self._get_llm_call_params(),
prompt=prompt, prompt=prompt,
stream=True, stream=True,
timeout=self.time_out, incremental_output=True
temperature=self.temperature,
top_p=self.top_p,
incremental_output=True # 开启增量输出模式
) )
for response in responses: for response in responses:
@ -128,14 +114,11 @@ class LLMService:
yield f"error: {error_msg}" yield f"error: {error_msg}"
def _call_llm_api(self, prompt: str) -> Optional[str]: def _call_llm_api(self, prompt: str) -> Optional[str]:
"""调用阿里Qwen3大模型API非流式""" """调用阿里Qwen大模型API非流式"""
try: try:
response = dashscope.Generation.call( response = dashscope.Generation.call(
model=self.model_name, **self._get_llm_call_params(),
prompt=prompt, prompt=prompt
timeout=self.time_out,
temperature=self.temperature,
top_p=self.top_p
) )
if response.status_code == HTTPStatus.OK: if response.status_code == HTTPStatus.OK:

View File

@ -65,6 +65,47 @@ class SystemConfigService:
print(f"Error getting config {dict_code}: {e}") print(f"Error getting config {dict_code}: {e}")
return default_value return default_value
@classmethod
def get_config_attribute(cls, dict_code: str, attr_name: str, default_value: Any = None) -> Any:
"""
从指定配置记录的扩展属性中读取指定属性值
此方法用于处理扩展属性为复杂JSON的配置记录如llm_modelvoiceprint等
Args:
dict_code: 配置项编码 ( 'llm_model', 'voiceprint')
attr_name: 扩展属性中的属性名 ( 'time_out', 'channels', 'template_text')
default_value: 默认值如果配置或属性不存在则返回此值
Returns:
属性值
"""
try:
with get_db_connection() as conn:
cursor = conn.cursor(dictionary=True)
query = """
SELECT extension_attr
FROM dict_data
WHERE dict_type = %s AND dict_code = %s AND status = 1
LIMIT 1
"""
cursor.execute(query, (cls.DICT_TYPE, dict_code))
result = cursor.fetchone()
cursor.close()
if result and result['extension_attr']:
try:
ext_attr = json.loads(result['extension_attr']) if isinstance(result['extension_attr'], str) else result['extension_attr']
return ext_attr.get(attr_name, default_value)
except (json.JSONDecodeError, AttributeError):
pass
return default_value
except Exception as e:
print(f"Error getting config attribute {dict_code}.{attr_name}: {e}")
return default_value
@classmethod @classmethod
def set_config(cls, dict_code: str, value: Any, label_cn: str = None) -> bool: def set_config(cls, dict_code: str, value: Any, label_cn: str = None) -> bool:
""" """
@ -181,15 +222,16 @@ class SystemConfigService:
"""获取ASR热词字典ID""" """获取ASR热词字典ID"""
return cls.get_config(cls.ASR_VOCABULARY_ID) return cls.get_config(cls.ASR_VOCABULARY_ID)
# 声纹配置获取方法(直接使用通用方法)
@classmethod @classmethod
def get_voiceprint_template(cls, default: str = "我正在进行声纹采集,这段语音将用于身份识别和验证。\n\n声纹技术能够准确识别每个人独特的声音特征。") -> str: def get_voiceprint_template(cls, default: str = "我正在进行声纹采集,这段语音将用于身份识别和验证。\n\n声纹技术能够准确识别每个人独特的声音特征。") -> str:
"""获取声纹采集模版""" """获取声纹采集模版"""
return cls.get_config(cls.VOICEPRINT_TEMPLATE_TEXT, default) return cls.get_config_attribute('voiceprint', 'template_text', default)
@classmethod @classmethod
def get_voiceprint_max_size(cls, default: int = 5242880) -> int: def get_voiceprint_max_size(cls, default: int = 5242880) -> int:
"""获取声纹文件大小限制 (bytes), 默认5MB""" """获取声纹文件大小限制 (bytes), 默认5MB"""
value = cls.get_config(cls.VOICEPRINT_MAX_SIZE, default) value = cls.get_config_attribute('voiceprint', 'voiceprint_max_size', default)
try: try:
return int(value) return int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -198,7 +240,7 @@ class SystemConfigService:
@classmethod @classmethod
def get_voiceprint_duration(cls, default: int = 12) -> int: def get_voiceprint_duration(cls, default: int = 12) -> int:
"""获取声纹采集最短时长 (秒)""" """获取声纹采集最短时长 (秒)"""
value = cls.get_config(cls.VOICEPRINT_DURATION, default) value = cls.get_config_attribute('voiceprint', 'duration_seconds', default)
try: try:
return int(value) return int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -207,7 +249,7 @@ class SystemConfigService:
@classmethod @classmethod
def get_voiceprint_sample_rate(cls, default: int = 16000) -> int: def get_voiceprint_sample_rate(cls, default: int = 16000) -> int:
"""获取声纹采样率""" """获取声纹采样率"""
value = cls.get_config(cls.VOICEPRINT_SAMPLE_RATE, default) value = cls.get_config_attribute('voiceprint', 'sample_rate', default)
try: try:
return int(value) return int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -216,7 +258,7 @@ class SystemConfigService:
@classmethod @classmethod
def get_voiceprint_channels(cls, default: int = 1) -> int: def get_voiceprint_channels(cls, default: int = 1) -> int:
"""获取声纹通道数""" """获取声纹通道数"""
value = cls.get_config(cls.VOICEPRINT_CHANNELS, default) value = cls.get_config_attribute('voiceprint', 'channels', default)
try: try:
return int(value) return int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -245,16 +287,16 @@ class SystemConfigService:
except (ValueError, TypeError): except (ValueError, TypeError):
return default return default
# LLM模型配置获取方法 # LLM模型配置获取方法(直接使用通用方法)
@classmethod @classmethod
def get_llm_model_name(cls, default: str = "qwen-plus") -> str: def get_llm_model_name(cls, default: str = "qwen-plus") -> str:
"""获取LLM模型名称""" """获取LLM模型名称"""
return cls.get_config(cls.LLM_MODEL_NAME, default) return cls.get_config_attribute('llm_model', 'model_name', default)
@classmethod @classmethod
def get_llm_timeout(cls, default: int = 120) -> int: def get_llm_timeout(cls, default: int = 300) -> int:
"""获取LLM超时时间""" """获取LLM超时时间"""
value = cls.get_config(cls.LLM_TIMEOUT, str(default)) value = cls.get_config_attribute('llm_model', 'time_out', default)
try: try:
return int(value) return int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -263,7 +305,7 @@ class SystemConfigService:
@classmethod @classmethod
def get_llm_temperature(cls, default: float = 0.7) -> float: def get_llm_temperature(cls, default: float = 0.7) -> float:
"""获取LLM temperature参数""" """获取LLM temperature参数"""
value = cls.get_config(cls.LLM_TEMPERATURE, str(default)) value = cls.get_config_attribute('llm_model', 'temperature', default)
try: try:
return float(value) return float(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -272,7 +314,7 @@ class SystemConfigService:
@classmethod @classmethod
def get_llm_top_p(cls, default: float = 0.9) -> float: def get_llm_top_p(cls, default: float = 0.9) -> float:
"""获取LLM top_p参数""" """获取LLM top_p参数"""
value = cls.get_config(cls.LLM_TOP_P, str(default)) value = cls.get_config_attribute('llm_model', 'top_p', default)
try: try:
return float(value) return float(value)
except (ValueError, TypeError): except (ValueError, TypeError):