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
| from typing import TYPE_CHECKING
|
| from plugins_func.register import register_function, ToolType, ActionResponse, Action
| from core.app_runtime.runtime import TRANSLATOR_PROMPT
|
| if TYPE_CHECKING:
| from core.connection import ConnectionHandler
|
| translate_function_desc = {
| "type": "function",
| "function": {
| "name": "translate",
| "description": "把用户这句话翻译成另一种语言。只返回译文。中文译英文,英文译中文。不要解释。",
| "parameters": {
| "type": "object",
| "properties": {
| "text": {"type": "string", "description": "要翻译的原文"},
| "source_lang": {
| "type": "string",
| "description": "源语言代码,可空;空则自动判断",
| },
| "target_lang": {
| "type": "string",
| "description": "目标语言代码,可空;空则中文↔英文",
| },
| },
| "required": ["text"],
| },
| },
| }
|
|
| def _build_user_prompt(text: str, source_lang: str, target_lang: str) -> str:
| extra = ""
| if source_lang or target_lang:
| extra = f"\n源语言:{source_lang or 'auto'} 目标语言:{target_lang or 'auto'}"
| return f"翻译下面内容,只输出译文:{extra}\n{text}"
|
|
| @register_function("translate", translate_function_desc, ToolType.SYSTEM_CTL)
| def translate(
| conn: "ConnectionHandler",
| text: str,
| source_lang: str = "",
| target_lang: str = "",
| ):
| llm = getattr(conn, "llm", None)
| if not llm or not text:
| return ActionResponse(action=Action.ERROR, response="翻译服务不可用")
| try:
| out = llm.response_no_stream(
| TRANSLATOR_PROMPT,
| _build_user_prompt(text, source_lang or "", target_lang or ""),
| temperature=0.1,
| )
| out = (out or "").strip()
| if not out:
| return ActionResponse(action=Action.ERROR, response="没有得到译文")
| return ActionResponse(action=Action.RESPONSE, result=out, response=out)
| except Exception as e:
| return ActionResponse(action=Action.ERROR, response=str(e))
|
|