MCPcopy Create free account
hub / github.com/OpenRaiser/PaperFlow / save_chat_message

Function save_chat_message

skills/storage-helper/scripts/db_ops.py:329–410  ·  view source on GitHub ↗

Persist a GUI chat message and update its parent session summary.

(
    user_id: str,
    session_id: str,
    role: str,
    content: str,
    metadata: Optional[Dict[str, Any]] = None,
)

Source from the content-addressed store, hash-verified

327
328
329def save_chat_message(
330 user_id: str,
331 session_id: str,
332 role: str,
333 content: str,
334 metadata: Optional[Dict[str, Any]] = None,
335) -> Dict[str, Any]:
336 """Persist a GUI chat message and update its parent session summary."""
337 normalized_user_id = _normalize_identifier(user_id)
338 normalized_session_id = _normalize_identifier(session_id)
339 normalized_role = str(role or "").strip().lower()
340 if not normalized_user_id or not normalized_session_id:
341 raise ValueError("user_id and session_id are required")
342 if normalized_role not in {"user", "assistant"}:
343 raise ValueError("role must be user or assistant")
344
345 ensure_chat_tables()
346 create_chat_session(normalized_user_id, str(content or ""), normalized_session_id)
347
348 now = _chat_now()
349 conn = get_connection()
350 cursor = conn.cursor()
351 cursor.execute(
352 """
353 INSERT INTO chat_messages (session_id, user_id, role, content, metadata, created_at)
354 VALUES (?, ?, ?, ?, ?, ?)
355 """,
356 (
357 normalized_session_id,
358 normalized_user_id,
359 normalized_role,
360 str(content or ""),
361 json.dumps(metadata or {}, ensure_ascii=False),
362 now,
363 ),
364 )
365 message_id = cursor.lastrowid
366 if normalized_role == "user":
367 cursor.execute(
368 """
369 UPDATE chat_sessions
370 SET title = CASE WHEN title IN ('', '新对话', 'New chat') THEN ? ELSE title END,
371 updated_at = ?
372 WHERE user_id = ? AND session_id = ?
373 """,
374 (_chat_title_from_content(content), now, normalized_user_id, normalized_session_id),
375 )
376 else:
377 cursor.execute(
378 """
379 UPDATE chat_sessions
380 SET updated_at = ?
381 WHERE user_id = ? AND session_id = ?
382 """,
383 (now, normalized_user_id, normalized_session_id),
384 )
385 cursor.execute(
386 """

Callers

nothing calls this directly

Calls 11

_normalize_identifierFunction · 0.85
ensure_chat_tablesFunction · 0.85
_chat_nowFunction · 0.85
_chat_title_from_contentFunction · 0.85
_load_json_metadataFunction · 0.85
cursorMethod · 0.80
getMethod · 0.80
create_chat_sessionFunction · 0.70
get_connectionFunction · 0.70
executeMethod · 0.45
closeMethod · 0.45

Tested by

no test coverage detected