1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
| class ModelType(Enum):
"""
模型类型枚举
定义Dify支持的所有AI模型类型
"""
# 大语言模型 - 文本生成和对话
LLM = "llm"
# 文本嵌入模型 - 向量化文本
TEXT_EMBEDDING = "text-embedding"
# 重排序模型 - 文档相关性重排序
RERANK = "rerank"
# 语音转文字模型 - 音频转录
SPEECH2TEXT = "speech2text"
# 文字转语音模型 - 语音合成
TTS = "tts"
# 内容审核模型 - 内容安全检测
MODERATION = "moderation"
# 模型类型特性对比
model_type_features = {
"llm": {
"description": "大语言模型,支持文本生成、对话和推理",
"primary_function": "text_generation",
"input_types": ["text", "image", "audio"],
"output_types": ["text", "function_calls"],
"key_features": [
"多轮对话", "函数调用", "代码生成",
"内容创作", "推理问答", "多模态理解"
],
"providers": [
"openai", "anthropic", "google", "azure_openai",
"zhipuai", "tongyi", "wenxin", "moonshot", "ollama"
],
"typical_models": [
"gpt-4", "claude-3", "gemini-pro",
"qwen-plus", "ernie-4.0", "moonshot-v1"
]
},
"text-embedding": {
"description": "文本嵌入模型,将文本转换为高维向量表示",
"primary_function": "text_vectorization",
"input_types": ["text"],
"output_types": ["vector"],
"key_features": [
"语义相似度计算", "文档检索", "聚类分析",
"推荐系统", "异常检测"
],
"providers": [
"openai", "google", "cohere", "jina",
"zhipuai", "tongyi", "bge", "m3e"
],
"typical_models": [
"text-embedding-3-large", "embedding-001",
"embed-multilingual-v3.0", "bge-large-zh"
]
},
"rerank": {
"description": "重排序模型,对检索结果按相关性重新排序",
"primary_function": "relevance_ranking",
"input_types": ["query_document_pairs"],
"output_types": ["relevance_scores"],
"key_features": [
"检索结果优化", "相关性评分", "排序算法",
"多语言支持", "跨域泛化"
],
"providers": [
"cohere", "jina", "voyage", "xinference",
"bge", "bce"
],
"typical_models": [
"rerank-english-v3.0", "jina-reranker-v1-base",
"voyage-rerank-lite", "bge-reranker-large"
]
},
"speech2text": {
"description": "语音转文字模型,将音频转录为文本",
"primary_function": "audio_transcription",
"input_types": ["audio"],
"output_types": ["text"],
"key_features": [
"多语言识别", "实时转录", "标点符号",
"说话人识别", "噪声处理"
],
"providers": [
"openai", "azure_openai", "google",
"alibaba", "baidu", "iflytek"
],
"typical_models": [
"whisper-1", "whisper-large-v3",
"speech-recognition-v1", "asr-v1"
]
},
"tts": {
"description": "文字转语音模型,将文本合成为语音",
"primary_function": "speech_synthesis",
"input_types": ["text"],
"output_types": ["audio"],
"key_features": [
"多音色选择", "情感表达", "语速控制",
"多语言合成", "高保真音质"
],
"providers": [
"openai", "azure_openai", "google",
"alibaba", "baidu", "iflytek", "elevenlabs"
],
"typical_models": [
"tts-1", "tts-1-hd", "neural-voice",
"speech-synthesis-v1"
]
},
"moderation": {
"description": "内容审核模型,检测文本内容的安全性",
"primary_function": "content_safety_detection",
"input_types": ["text"],
"output_types": ["safety_scores"],
"key_features": [
"有害内容检测", "敏感信息识别", "多维度评分",
"实时审核", "合规性检查"
],
"providers": [
"openai", "azure_openai", "google",
"alibaba", "baidu", "tencent"
],
"typical_models": [
"text-moderation-latest", "content-safety-v1",
"moderation-api"
]
}
}
class LargeLanguageModel(AIModel):
"""
大语言模型基类
定义所有LLM提供者的通用接口
"""
model_type: ModelType = ModelType.LLM
@abstractmethod
def invoke(
self,
model: str,
credentials: dict[str, Any],
prompt_messages: list[PromptMessage],
model_parameters: Optional[dict] = None,
tools: Optional[list[PromptMessageTool]] = None,
stop: Optional[list[str]] = None,
stream: bool = True,
user: Optional[str] = None,
callbacks: Optional[list[Callback]] = None,
) -> Union[LLMResult, Generator[LLMResultChunk, None, None]]:
"""
调用大语言模型
子类必须实现的核心调用方法
Args:
model: 模型名称
credentials: 模型凭据
prompt_messages: 提示消息列表
model_parameters: 模型参数(温度、最大令牌等)
tools: 工具列表(用于函数调用)
stop: 停止词列表
stream: 是否流式输出
user: 用户标识
callbacks: 回调函数列表
Returns:
Union[LLMResult, Generator]: LLM调用结果
"""
raise NotImplementedError("子类必须实现invoke方法")
@abstractmethod
def get_num_tokens(
self,
model: str,
credentials: dict[str, Any],
prompt_messages: list[PromptMessage],
tools: Optional[list[PromptMessageTool]] = None,
) -> int:
"""
获取提示消息的令牌数量
用于成本计算和上下文长度管理
Args:
model: 模型名称
credentials: 模型凭据
prompt_messages: 提示消息列表
tools: 工具列表
Returns:
int: 令牌总数
"""
raise NotImplementedError("子类必须实现get_num_tokens方法")
def validate_credentials(
self,
model: str,
credentials: dict[str, Any]
) -> bool:
"""
验证模型凭据
检查提供的凭据是否能够成功调用模型
Args:
model: 模型名称
credentials: 凭据字典
Returns:
bool: 凭据是否有效
"""
try:
# 使用简单的测试提示验证凭据
test_messages = [
UserPromptMessage(content="Hello")
]
# 调用模型(非流式,最小参数)
result = self.invoke(
model=model,
credentials=credentials,
prompt_messages=test_messages,
model_parameters={"max_tokens": 1, "temperature": 0},
stream=False,
user="system_validation"
)
return True
except Exception as e:
logger.warning(f"凭据验证失败: {e}")
return False
def get_model_schema(
self,
model: str,
credentials: dict[str, Any]
) -> Optional[AIModelEntity]:
"""
获取模型schema
返回模型的能力、参数规则和限制信息
Args:
model: 模型名称
credentials: 模型凭据
Returns:
Optional[AIModelEntity]: 模型实体,包含完整的模型信息
"""
# 首先从预定义模型中查找
predefined_models = self.get_predefined_models()
for predefined_model in predefined_models:
if predefined_model.model == model:
return predefined_model
# 如果支持远程模型,尝试获取
if hasattr(self, 'get_remote_models'):
try:
remote_models = self.get_remote_models(credentials)
for remote_model in remote_models:
if remote_model.model == model:
return remote_model
except Exception as e:
logger.warning(f"获取远程模型schema失败: {e}")
return None
def calculate_cost(
self,
model: str,
prompt_tokens: int,
completion_tokens: int
) -> float:
"""
计算调用成本
根据令牌数量和模型定价计算成本
Args:
model: 模型名称
prompt_tokens: 提示令牌数
completion_tokens: 完成令牌数
Returns:
float: 调用成本(美元)
"""
model_schema = self.get_model_schema(model, {})
if not model_schema or not model_schema.pricing:
return 0.0
pricing = model_schema.pricing
# 计算提示成本
prompt_cost = (prompt_tokens / 1000000) * pricing.input_price
# 计算完成成本
completion_cost = (completion_tokens / 1000000) * pricing.output_price
return prompt_cost + completion_cost
class TextEmbeddingModel(AIModel):
"""
文本嵌入模型基类
定义文本向量化的通用接口
"""
model_type: ModelType = ModelType.TEXT_EMBEDDING
@abstractmethod
def invoke(
self,
model: str,
credentials: dict[str, Any],
texts: list[str],
user: Optional[str] = None,
input_type: EmbeddingInputType = EmbeddingInputType.DOCUMENT,
) -> TextEmbeddingResult:
"""
调用文本嵌入模型
Args:
model: 模型名称
credentials: 模型凭据
texts: 待嵌入的文本列表
user: 用户标识
input_type: 输入类型,影响嵌入优化策略
Returns:
TextEmbeddingResult: 嵌入结果
"""
raise NotImplementedError("子类必须实现invoke方法")
@abstractmethod
def get_num_tokens(
self,
model: str,
credentials: dict[str, Any],
texts: list[str]
) -> list[int]:
"""
获取文本令牌数量
Args:
model: 模型名称
credentials: 模型凭据
texts: 文本列表
Returns:
list[int]: 每个文本的令牌数量
"""
raise NotImplementedError("子类必须实现get_num_tokens方法")
def batch_embed_with_optimization(
self,
model: str,
credentials: dict[str, Any],
texts: list[str],
batch_size: int = 100,
user: Optional[str] = None,
input_type: EmbeddingInputType = EmbeddingInputType.DOCUMENT,
) -> TextEmbeddingResult:
"""
批量嵌入优化
对大量文本进行分批处理,避免API限制
Args:
model: 模型名称
credentials: 模型凭据
texts: 待嵌入的文本列表
batch_size: 批次大小
user: 用户标识
input_type: 输入类型
Returns:
TextEmbeddingResult: 合并的嵌入结果
"""
if len(texts) <= batch_size:
# 小于批次大小,直接调用
return self.invoke(
model=model,
credentials=credentials,
texts=texts,
user=user,
input_type=input_type
)
# 分批处理
all_embeddings = []
total_tokens = 0
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
batch_result = self.invoke(
model=model,
credentials=credentials,
texts=batch_texts,
user=user,
input_type=input_type
)
all_embeddings.extend(batch_result.embeddings)
total_tokens += batch_result.usage.total_tokens
# 合并结果
return TextEmbeddingResult(
embeddings=all_embeddings,
usage=EmbeddingUsage(
tokens=total_tokens,
total_price=self._calculate_embedding_cost(model, total_tokens)
)
)
class RerankModel(AIModel):
"""
重排序模型基类
对检索结果进行相关性重新排序
"""
model_type: ModelType = ModelType.RERANK
@abstractmethod
def invoke(
self,
model: str,
credentials: dict[str, Any],
query: str,
docs: list[str],
score_threshold: Optional[float] = None,
top_n: Optional[int] = None,
user: Optional[str] = None,
) -> RerankResult:
"""
调用重排序模型
Args:
model: 模型名称
credentials: 模型凭据
query: 搜索查询
docs: 待重排序的文档列表
score_threshold: 相关性分数阈值
top_n: 返回前N个结果
user: 用户标识
Returns:
RerankResult: 重排序结果
"""
raise NotImplementedError("子类必须实现invoke方法")
def batch_rerank(
self,
model: str,
credentials: dict[str, Any],
queries: list[str],
docs_list: list[list[str]],
score_threshold: Optional[float] = None,
top_n: Optional[int] = None,
user: Optional[str] = None,
) -> list[RerankResult]:
"""
批量重排序
同时处理多个查询的重排序任务
Args:
model: 模型名称
credentials: 模型凭据
queries: 查询列表
docs_list: 对应的文档列表
score_threshold: 分数阈值
top_n: 返回数量
user: 用户标识
Returns:
list[RerankResult]: 重排序结果列表
"""
results = []
for query, docs in zip(queries, docs_list):
try:
result = self.invoke(
model=model,
credentials=credentials,
query=query,
docs=docs,
score_threshold=score_threshold,
top_n=top_n,
user=user
)
results.append(result)
except Exception as e:
logger.warning(f"重排序失败 - 查询: {query[:50]}..., 错误: {e}")
# 返回空结果作为备选
results.append(RerankResult(docs=[]))
return results
class TTSModel(AIModel):
"""
文字转语音模型基类
文本到语音合成的通用接口
"""
model_type: ModelType = ModelType.TTS
@abstractmethod
def invoke(
self,
model: str,
credentials: dict[str, Any],
content_text: str,
user: Optional[str] = None,
tenant_id: Optional[str] = None,
voice: Optional[str] = None,
) -> Iterable[bytes]:
"""
调用文字转语音模型
Args:
model: 模型名称
credentials: 模型凭据
content_text: 待合成的文本内容
user: 用户标识
tenant_id: 租户ID
voice: 语音音色
Returns:
Iterable[bytes]: 音频数据流
"""
raise NotImplementedError("子类必须实现invoke方法")
@abstractmethod
def get_tts_model_voices(
self,
model: str,
credentials: dict[str, Any],
language: Optional[str] = None
) -> list[dict]:
"""
获取TTS模型支持的语音列表
Args:
model: 模型名称
credentials: 模型凭据
language: 可选的语言过滤
Returns:
list[dict]: 语音列表,包含音色信息
"""
raise NotImplementedError("子类必须实现get_tts_model_voices方法")
def synthesize_long_text(
self,
model: str,
credentials: dict[str, Any],
content_text: str,
voice: str,
max_chunk_length: int = 1000,
user: Optional[str] = None,
tenant_id: Optional[str] = None,
) -> Iterable[bytes]:
"""
长文本语音合成
将长文本分块进行语音合成,避免长度限制
Args:
model: 模型名称
credentials: 模型凭据
content_text: 长文本内容
voice: 语音音色
max_chunk_length: 最大块长度
user: 用户标识
tenant_id: 租户ID
Yields:
bytes: 音频数据块
"""
# 智能分块,避免在句子中间断开
text_chunks = self._smart_split_text(content_text, max_chunk_length)
for chunk in text_chunks:
if chunk.strip():
try:
# 合成当前块
audio_stream = self.invoke(
model=model,
credentials=credentials,
content_text=chunk,
user=user,
tenant_id=tenant_id,
voice=voice
)
# 输出音频数据
for audio_chunk in audio_stream:
yield audio_chunk
except Exception as e:
logger.warning(f"文本块合成失败: {e}")
continue
def _smart_split_text(self, text: str, max_length: int) -> list[str]:
"""
智能文本分块
在句子边界处分割,保持语义完整性
Args:
text: 原始文本
max_length: 最大块长度
Returns:
list[str]: 分割后的文本块
"""
if len(text) <= max_length:
return [text]
chunks = []
sentences = re.split(r'[。!?.!?]', text)
current_chunk = ""
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
# 检查是否可以添加到当前块
if len(current_chunk + sentence) <= max_length:
current_chunk += sentence + "。"
else:
# 当前块已满,开始新块
if current_chunk:
chunks.append(current_chunk)
current_chunk = sentence + "。"
# 添加最后一块
if current_chunk:
chunks.append(current_chunk)
return chunks
class ModerationModel(AIModel):
"""
内容审核模型基类
检测文本内容的安全性和合规性
"""
model_type: ModelType = ModelType.MODERATION
@abstractmethod
def invoke(
self,
model: str,
credentials: dict[str, Any],
text: str,
user: Optional[str] = None,
) -> bool:
"""
调用内容审核模型
Args:
model: 模型名称
credentials: 模型凭据
text: 待审核的文本
user: 用户标识
Returns:
bool: True表示内容有问题,False表示内容安全
"""
raise NotImplementedError("子类必须实现invoke方法")
def batch_moderate(
self,
model: str,
credentials: dict[str, Any],
texts: list[str],
user: Optional[str] = None,
) -> list[bool]:
"""
批量内容审核
同时审核多个文本
Args:
model: 模型名称
credentials: 模型凭据
texts: 待审核的文本列表
user: 用户标识
Returns:
list[bool]: 每个文本的审核结果
"""
results = []
for text in texts:
try:
result = self.invoke(
model=model,
credentials=credentials,
text=text,
user=user
)
results.append(result)
except Exception as e:
logger.warning(f"文本审核失败: {e}")
# 出错时标记为有问题,确保安全
results.append(True)
return results
def get_moderation_details(
self,
model: str,
credentials: dict[str, Any],
text: str,
user: Optional[str] = None,
) -> dict[str, Any]:
"""
获取详细的审核信息
返回各个维度的审核分数和原因
Args:
model: 模型名称
credentials: 模型凭据
text: 待审核文本
user: 用户标识
Returns:
dict[str, Any]: 详细审核信息
"""
# 基础实现,子类可以覆盖以提供更详细的信息
is_flagged = self.invoke(model, credentials, text, user)
return {
"flagged": is_flagged,
"categories": {}, # 子类应该提供具体的分类信息
"scores": {}, # 子类应该提供具体的分数信息
}
|