query.py
26 KB
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
import asyncio
import json
import logging
import os
import re
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from fastapi import APIRouter, Body, HTTPException
from fastapi.responses import StreamingResponse
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg
from agentscope.tool import Toolkit
from config import QUERY_MODEL_NAME
from src.database.models import WikiQueryLog
from src.database.session import AsyncSessionLocal
from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file
from src.utils.llm_tracker import get_llm_model, load_skill_prompt, print_thinking, token_counter_context
logger = logging.getLogger(__name__)
router = APIRouter()
# 环境变量读取配置项
QUERY_TIMEOUT_SECONDS = int(os.environ.get("WIKI_QUERY_TIMEOUT_SECONDS", "180")) # 查询超时时间,默认 180 秒
HEARTBEAT_SECONDS = int(os.environ.get("WIKI_QUERY_HEARTBEAT_SECONDS", "15")) # SSE 流式输出的心跳间隔时间,默认 15 秒
STREAM_CHUNK_SIZE = int(os.environ.get("WIKI_QUERY_STREAM_CHUNK_SIZE", "8")) # 流式输出文本时的分块大小,默认 8 个字符
EMPTY_ANSWER_FALLBACK = "知识库查询没有生成有效回答,请稍后重试,或补充更明确的问题信息。" # 兜底回答文本
@dataclass
class WikiQueryResult:
"""用于封装 Wiki 查询返回的结果数据结构"""
answer: str # 最终返回的答案
tokens: int # 本次请求消耗的 token 数量
duration_ms: int # 查询总耗时(毫秒)
status: str = "Success" # 执行状态(Success, Error, Timeout, EmptyAnswer)
error: str | None = None # 错误信息(如果有)
reasoning: list[dict[str, Any]] = field(default_factory=list) # Agent 的执行推理过程事件流记录
async def save_query_log_to_db(
query: str,
history: list,
answer: str | None,
model: str,
tokens: int,
duration_ms: int,
status: str = "Success",
error: str | None = None,
session_id: str | None = None,
) -> None:
"""
异步将查询记录保存至数据库中。
内部使用异常捕获以确保失败仅记录日志,不会阻塞或影响用户的正常接口响应。
"""
try:
async with AsyncSessionLocal() as session:
# 构造数据库日志对象
log = WikiQueryLog(
session_id=session_id,
query_text=query,
history=json.dumps(history, ensure_ascii=False) if history else None,
answer_text=answer,
model_name=model,
total_tokens=tokens,
duration_ms=duration_ms,
status=status,
error_message=error,
)
session.add(log)
await session.commit()
logger.info("查询日志已入库: id=%s, status=%s", getattr(log, "id", None), status)
if answer:
logger.info("[Query Result] query=%r, answer_chars=%s", query, len(answer))
except Exception as exc:
logger.exception("写入查询日志到数据库失败: %s", exc)
@router.post("/wiki/query")
async def wiki_query(data: dict = Body(...)):
"""
Wiki 查询接口(SSE 流式响应)。
用于前端实时接收模型打字机效果及推理过程心跳。
"""
user_query = str(data.get("query", "")).strip()
history = data.get("history") or []
session_id = data.get("sessionId")
logger.info(
"收到 Wiki 查询请求: query=%r, session_id=%r, history_len=%s",
user_query,
session_id,
len(history),
)
if not user_query:
raise HTTPException(status_code=400, detail="Query is empty")
# 返回 StreamingResponse,启用流式事件输出
return StreamingResponse(
run_wiki_query_stream(user_query, history, session_id),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache", # 禁用缓存
"X-Accel-Buffering": "no", # 禁用 Nginx 等反向代理的缓存以保证实时性
},
)
@router.post("/wiki/query/json")
async def wiki_query_json_endpoint(data: dict = Body(...)):
"""
Wiki 查询接口(JSON 同步响应)。
供不需要流式输出的客户端调用,直接等待查询结束后返回完整结果。
"""
user_query = str(data.get("query", "")).strip()
history = data.get("history") or []
session_id = data.get("sessionId")
logger.info(
"收到 Wiki JSON 查询请求: query=%r, session_id=%r, history_len=%s",
user_query,
session_id,
len(history),
)
if not user_query:
raise HTTPException(status_code=400, detail="Query is empty")
try:
# 同步等待查询执行结束
result = await run_wiki_query_json(user_query, history, session_id)
except Exception as exc:
logger.exception("JSON 查询执行失败: %s", exc)
raise HTTPException(status_code=500, detail=str(exc)) from exc
return {
"answer": result.answer,
"tokens": result.tokens,
"duration_ms": result.duration_ms,
"status": result.status,
}
def build_query_agent(history: list) -> ReActAgent:
"""
构建并配置用于检索 Wiki 的 AgentScope ReAct 智能体。
为智能体装载本地文件读取和搜索工具,并注入特定业务的 System Prompt。
"""
toolkit = Toolkit()
# 注册智能体可使用的工具
toolkit.register_tool_function(grep_wiki_files) # 全文正则搜索
toolkit.register_tool_function(glob_wiki_files) # 文件名匹配搜索
toolkit.register_tool_function(read_local_file) # 读取文件内容
# 加载针对 llm-query 定制的提示词片段
skill_prompt = load_skill_prompt("llm-query")
# 注入前置历史会话上下文
history_injection = ""
if history:
history_lines = []
# 只保留最近 16 条对话记录
for item in history[-16:]:
role_label = "用户" if item.get("role") == "user" else "助手"
# 限制历史文本长度,避免 Token 消耗过大
content = str(item.get("content", ""))[:500]
history_lines.append(f"{role_label}: {content}")
history_injection = (
"\n\n【对话历史】用于理解用户当前上下文:\n"
+ "\n".join(history_lines)
+ "\n"
)
# 定义完整的系统提示词
sys_prompt = f"""你是一名专业的汽车后市场服务知识顾问。你的任务是基于知识库精确回答用户问题。
{history_injection}
【工作流程】
1. 先分析用户问题的意图(产品、话术、政策、流程、排障等)。
2. 使用 grep_wiki_files / glob_wiki_files / read_local_file 工具在 ware/wiki 中检索。
3. 完成检索后,直接基于找到的内容生成专业、准确的最终回答。
【严格约束】
- 只使用知识库中的信息回答,禁止编造或臆测。
- 价格、年限、里程等数字必须与知识库原文完全一致,禁止四舍五入。
- 如果知识库信息不足以回答,明确告知用户并建议补充哪类文档。
- 区分不同品牌/车型,不得混淆信息。
- 当用户问题模糊时(如不确定品牌/产品),先反问确认再检索。
- 最终回答只放在最终答案中;思考过程、工具调用和工具返回不要混入最终答案。
{skill_prompt}
"""
return ReActAgent(
name="WikiAssistant",
model=get_llm_model(QUERY_MODEL_NAME),
formatter=DashScopeChatFormatter(),
sys_prompt=sys_prompt,
toolkit=toolkit,
)
class WikiQueryRunner:
"""
执行核心查询逻辑的运行器类,负责调度 Agent,处理各类过程事件并记录。
支持可选将事件抛出到异步队列以供流式接口使用。
"""
def __init__(
self,
user_query: str,
history: list,
session_id: str | None = None,
event_queue: asyncio.Queue | None = None,
) -> None:
self.user_query = user_query
self.history = history
self.session_id = session_id
self.event_queue = event_queue
self.reasoning: list[dict[str, Any]] = [] # 收集的所有推理事件
self._reasoning_latest: dict[str, dict[str, Any]] = {} # 最新状态的推理事件(按 ID 索引)
self._reasoning_logged = False # 标记是否已经记录过最终的推理总结日志
self._logged_call_events: set[str] = set() # 记录已打印日志的工具调用事件,用于防重
async def execute(self) -> WikiQueryResult:
"""主执行入口,启动 Agent 进行问题解答,捕获状态并保存数据库日志。"""
start_time = time.time()
answer = ""
status = "Success"
error_msg: str | None = None
total_tokens = 0
# 进入 Token 统计上下文,方便在结束时获取请求消耗
async with token_counter_context() as get_tokens:
try:
agent = build_query_agent(self.history)
self._configure_agent(agent)
user_msg = Msg("user", self.user_query, role="user")
# 设置上下文标识,记录内部 thinking 打印状态
thinking_token = print_thinking.set(False)
try:
# 调用 Agent 进行查询,设定超时控制
final_res = await asyncio.wait_for(agent(user_msg), timeout=QUERY_TIMEOUT_SECONDS)
finally:
# 恢复上下文标识
print_thinking.reset(thinking_token)
# 提取并清理最终答案
answer = clean_final_answer(extract_text(final_res.content if hasattr(final_res, "content") else final_res))
# 如果没有生成实质答案,则进行兜底处理
if not answer:
status = "EmptyAnswer"
answer = EMPTY_ANSWER_FALLBACK
logger.warning("[Query] Agent 返回空答案,已使用兜底回答: query=%r", self.user_query)
# 打印整个过程的推理摘要日志
self._log_reasoning_summary(answer)
# 以流的形式发送答案
await self._emit_answer(answer)
logger.info("[Agent WikiAssistant Final Answer]\n%s", answer)
except asyncio.TimeoutError as exc:
status = "Timeout"
error_msg = f"查询超时({QUERY_TIMEOUT_SECONDS} 秒),请稍后重试或缩小问题范围。"
self._log_reasoning_summary(answer)
logger.exception("[Query] 查询超时: query=%r", self.user_query)
raise RuntimeError(error_msg) from exc
except Exception as exc:
status = "Error"
error_msg = str(exc)
self._log_reasoning_summary(answer)
logger.exception("[Query] 查询执行异常: %s", exc)
raise
finally:
# 无论成功失败,记录 token 用量、耗时并执行入库
total_tokens = get_tokens()
duration_ms = int((time.time() - start_time) * 1000)
save_log_coro = save_query_log_to_db(
self.user_query,
self.history,
answer or None,
QUERY_MODEL_NAME,
total_tokens,
duration_ms,
status,
error_msg,
self.session_id,
)
# 如果有队列说明是流式请求,以非阻塞 Task 异步执行入库
if self.event_queue:
asyncio.create_task(save_log_coro)
else:
await save_log_coro
logger.info(
"[Query] 查询结束: status=%s, tokens=%s, duration_ms=%s",
status,
total_tokens,
duration_ms,
)
return WikiQueryResult(
answer=answer,
tokens=total_tokens,
duration_ms=int((time.time() - start_time) * 1000),
status=status,
error=error_msg,
reasoning=self.reasoning,
)
def _configure_agent(self, agent: ReActAgent) -> None:
"""配置 Agent:接管自带的打印功能,将其转换为我们的流式事件用于前端展示和日志。"""
if hasattr(agent, "set_console_output_enabled"):
agent.set_console_output_enabled(False)
async def hooked_print(content: Any, *args: Any, **kwargs: Any) -> None:
# 捕获 Agent 发出的 Msg 事件
if isinstance(content, Msg):
# 解析事件流
for event in msg_to_reasoning_events(content):
event_id = str(event.get("id") or "")
# 避免推理过程中的事件在列表中重复(例如 agent 多次传入更新的同一对象)
existing_idx = next((i for i, e in enumerate(self.reasoning) if str(e.get("id") or "") == event_id), None) if event_id else None
if existing_idx is not None:
self.reasoning[existing_idx] = event
else:
self.reasoning.append(event)
self._remember_reasoning_event(event)
self._put_event(event) # 推送至 SSE 队列
event_type = event.get("type")
if event_type in {"call", "response"}:
# 日志去重,防止连续打印同样的工具调用
if event_id and event_id in self._logged_call_events:
continue
if event_id:
self._logged_call_events.add(event_id)
logger.info(
"[Agent %s %s] name=%s",
getattr(content, "name", "WikiAssistant"),
event_type,
event.get("name"),
)
# 拦截替换
agent.print = hooked_print
def _remember_reasoning_event(self, event: dict[str, Any]) -> None:
"""在本地记录一份最新的推理事件快照,用于生成最终的汇总日志"""
event_id = str(event.get("id") or f"event-{len(self._reasoning_latest)}")
self._reasoning_latest[event_id] = event
def _log_reasoning_summary(self, answer: str = "") -> None:
"""打印完整的推理过程汇总日志,避免过程中日志零散不直观"""
if self._reasoning_logged or not self._reasoning_latest:
return
blocks = []
for event in self._reasoning_latest.values():
# 去除与最终答案重复的 thinking 输出
if event.get("type") == "thought" and is_same_text(event.get("content", ""), answer):
continue
blocks.append(render_full_reasoning_log_event(event))
if blocks:
logger.info("[Agent WikiAssistant Reasoning]\n%s", "\n\n".join(blocks))
self._reasoning_logged = True
async def _emit_answer(self, answer: str) -> None:
"""将最终答案拆分为较小的 chunk 并发送至流式队列,模拟打字效果"""
if not self.event_queue:
return
msg_id = f"answer-{datetime.now().timestamp()}"
for index in range(0, len(answer), STREAM_CHUNK_SIZE):
delta = answer[index : index + STREAM_CHUNK_SIZE]
self._put_event({"id": msg_id, "type": "stream", "content": delta})
logger.debug("[Query] answer_delta: %s", preview_text(delta, 120))
await asyncio.sleep(0) # 让出执行权,避免阻塞
def _put_event(self, event: dict[str, Any]) -> None:
"""将事件放入异步队列(如果有的话)"""
if self.event_queue:
self.event_queue.put_nowait(event)
async def run_wiki_query_stream(user_query: str, history: list, session_id: str | None = None):
"""
流式执行 Wiki 查询的生成器函数。
向 SSE 客户端依次 yield 初始化、心跳、中间推理、打字片段及结束状态。
"""
# 发送初始化事件
yield "data: [INIT]\n\n"
queue: asyncio.Queue = asyncio.Queue()
runner = WikiQueryRunner(user_query, history, session_id=session_id, event_queue=queue)
# 异步启动查询任务
task = asyncio.create_task(runner.execute())
# 任务完成后向队列压入特殊标记,以便跳出接收循环
task.add_done_callback(lambda _task: queue.put_nowait({"type": "_task_done"}))
done_payload_sent = False
while True:
# 如果任务结束且队列已空,则退出
if task.done() and queue.empty():
break
try:
# 阻塞等待队列中的新事件,设定超时做心跳探测
item = await asyncio.wait_for(queue.get(), timeout=HEARTBEAT_SECONDS)
except asyncio.TimeoutError:
# 捕获到超时说明长时间无消息,发送心跳维持连接
if task.done() and queue.empty():
break
heartbeat = {
"type": "heartbeat",
"data": {"elapsed_ms": None, "ts": int(time.time() * 1000)},
}
yield sse_data(heartbeat)
continue
if isinstance(item, dict) and item.get("type") == "_task_done":
break
# 转发普通事件数据到前端
yield sse_data(item)
if task.done() and queue.empty():
break
try:
# 等待任务最终返回以获取统计信息
result = await task
done_payload_sent = True
yield sse_data(
{
"type": "done",
"data": {
"duration_ms": result.duration_ms,
"tokens": result.tokens,
"status": result.status,
},
}
)
except Exception as exc:
logger.exception("[Query] SSE 查询失败: %s", exc)
yield sse_data({"type": "error", "content": str(exc)})
finally:
# 如果任务被异常取消,发送报错
if not done_payload_sent and task.cancelled():
yield sse_data({"type": "error", "content": "查询任务已取消。"})
# 标准 SSE 结束标识
yield "data: [DONE]\n\n"
async def run_wiki_query_json(
user_query: str,
history: list,
session_id: str | None = None,
) -> WikiQueryResult:
"""内部执行直接获取 JSON 结果的包装函数"""
runner = WikiQueryRunner(user_query, history, session_id=session_id)
return await runner.execute()
def sse_data(payload: dict[str, Any]) -> str:
"""序列化格式化为 SSE (Server-Sent Events) 标准格式的字符串"""
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
def msg_to_reasoning_events(msg: Msg) -> list[dict[str, Any]]:
"""将 AgentScope 的 Msg 对象解析并转换为规范化的推理事件结构列表"""
# 忽略用户的原始提问消息
if getattr(msg, "role", None) == "user":
return []
msg_id = getattr(msg, "id", None) or f"msg-{datetime.now().timestamp()}"
content = getattr(msg, "content", "")
return content_to_reasoning_events(content, msg_id)
def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any]]:
"""
深度解析 Agent 的响应内容。
区分出 tool_use, tool_result, thinking, text 等不同类型的节点。
"""
events: list[dict[str, Any]] = []
# 列表递归拆解
if isinstance(content, list):
for index, item in enumerate(content):
events.extend(content_to_reasoning_events(item, f"{msg_id}-{index}"))
return events
# 字典格式解析:识别不同的行为 block
if isinstance(content, dict):
block_type = content.get("type")
if block_type == "tool_use":
# 工具调用事件
events.append(
{
"id": msg_id,
"type": "call",
"content": json.dumps(content, ensure_ascii=False),
"name": content.get("name"),
}
)
elif block_type == "tool_result":
# 工具返回结果事件
events.append(
{
"id": msg_id,
"type": "response",
"content": json.dumps(content, ensure_ascii=False),
"name": content.get("name"),
}
)
elif block_type == "thinking" or "thinking" in content:
# 模型内部的 thinking/推理过程
thinking = str(content.get("thinking", ""))
if thinking:
events.append({"id": msg_id, "type": "thought", "content": thinking})
elif block_type == "text" or "text" in content:
# 普通输出文本
text = str(content.get("text", ""))
if text and not is_final_answer_text(text):
events.append({"id": msg_id, "type": "thought", "content": text})
elif content:
# 兜底的字典项处理
events.append(
{
"id": msg_id,
"type": "thought",
"content": json.dumps(content, ensure_ascii=False),
}
)
return events
# 兜底纯文本处理
text = str(content).strip()
if text and not is_final_answer_text(text):
events.append({"id": msg_id, "type": "thought", "content": text})
return events
def extract_text(content: Any) -> str:
"""提取混合结构数据中的所有纯文本部分并拼接"""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if item.get("type") == "text" or "text" in item:
parts.append(str(item.get("text", "")))
else:
parts.append(extract_text(item))
return "".join(parts)
if isinstance(content, dict):
if content.get("type") == "text" or "text" in content:
return str(content.get("text", ""))
return ""
return str(content)
def clean_final_answer(text: str) -> str:
"""清理答案中的 thinking 标签和内部使用标记,输出整洁给用户的最终结果"""
text = text or ""
# 移除 <think>...</think> 相关内容
text = re.sub(r"<(?:think|thinking)>.*?</(?:think|thinking)>", "", text, flags=re.DOTALL | re.IGNORECASE)
# 移除头部的 Final Answer: 标识
text = re.sub(r"^\s*Final Answer\s*:\s*", "", text, flags=re.IGNORECASE)
return text.strip()
def is_final_answer_text(text: str) -> bool:
"""判断一段文本是否是以 Final Answer: 为前缀的标志性输出"""
return bool(re.match(r"^\s*Final Answer\s*:", text or "", flags=re.IGNORECASE))
def render_full_reasoning_log_event(event: dict[str, Any]) -> str:
"""格式化单条推理事件字典为美观的纯文本形式以供日志打印"""
event_type = event.get("type", "thought")
name = event.get("name")
event_id = event.get("id")
content = event.get("content", "")
parsed = parse_json_object(content)
if parsed and not name:
name = parsed.get("name")
header = f"--- [{event_type}{':' + str(name) if name else ''}]"
if event_id:
header += f" id={event_id}"
if parsed:
body = json.dumps(parsed, ensure_ascii=False, indent=2)
else:
body = str(content)
return f"{header}\n{body}"
def parse_json_object(value: Any) -> dict[str, Any]:
"""安全地解析 JSON 字符串为字典"""
if isinstance(value, dict):
return value
if not isinstance(value, str):
return {}
try:
parsed = json.loads(value)
except Exception:
return {}
return parsed if isinstance(parsed, dict) else {}
def extract_tool_output_text(output: Any) -> str:
"""从工具调用返回的混合数据中提取主要文本内容(日志或显示用)"""
if output is None:
return ""
if isinstance(output, str):
return output
if isinstance(output, list):
parts = []
for item in output:
if isinstance(item, dict) and "text" in item:
parts.append(str(item.get("text", "")))
else:
parts.append(extract_tool_output_text(item))
return "\n".join(part for part in parts if part)
if isinstance(output, dict):
if "text" in output:
return str(output.get("text", ""))
return json.dumps(output, ensure_ascii=False)
return str(output)
def is_same_text(left: Any, right: Any) -> bool:
"""比对两段文本去格式化后的核心内容是否一致"""
left_text = normalize_log_text(left)
right_text = normalize_log_text(right)
return bool(left_text and right_text and left_text == right_text)
def normalize_log_text(value: Any) -> str:
"""剔除空格和特殊标识,生成标准可比它的纯内容文本"""
return re.sub(r"\s+", "", clean_final_answer(str(value or "")))
def preview_text(text: Any, limit: int = 500) -> str:
"""文本截断预览,超过限制的补全省略号并消除换行以单行展示"""
value = str(text).replace("\r", "\\r").replace("\n", "\\n")
if len(value) <= limit:
return value
return value[:limit] + "...[truncated]"