MCPcopy
hub / github.com/NevaMind-AI/memU / format_references_as_citations

Function format_references_as_citations

src/memu/utils/references.py:77–115  ·  view source on GitHub ↗

Convert [ref:ID] format to numbered citations [1], [2], etc. Args: text: Text with [ref:ID] references Returns: Text with numbered citations and a reference list at the end Example: >>> format_references_as_citations("User loves coffee [ref:abc].")

(text: str | None)

Source from the content-addressed store, hash-verified

75
76
77def format_references_as_citations(text: str | None) -> str | None:
78 """
79 Convert [ref:ID] format to numbered citations [1], [2], etc.
80
81 Args:
82 text: Text with [ref:ID] references
83
84 Returns:
85 Text with numbered citations and a reference list at the end
86
87 Example:
88 >>> format_references_as_citations("User loves coffee [ref:abc].")
89 'User loves coffee [1].\\n\\nReferences:\\n[1] abc'
90 """
91 if not text:
92 return text
93
94 refs = extract_references(text)
95 if not refs:
96 return text
97
98 # Build ID to number mapping
99 id_to_num = {ref_id: idx + 1 for idx, ref_id in enumerate(refs)}
100
101 # Replace [ref:ID] with [N]
102 def replace_ref(match: re.Match) -> str:
103 ids_str = match.group(1)
104 nums = []
105 for item_id in ids_str.split(","):
106 item_id = item_id.strip()
107 if item_id in id_to_num:
108 nums.append(str(id_to_num[item_id]))
109 return f"[{','.join(nums)}]" if nums else ""
110
111 result = REFERENCE_PATTERN.sub(replace_ref, text)
112
113 # Add reference list at end
114 ref_list = "\n".join(f"[{num}] {ref_id}" for ref_id, num in id_to_num.items())
115 return f"{result}\n\nReferences:\n{ref_list}"
116
117
118def fetch_referenced_items(

Calls 2

extract_referencesFunction · 0.85
itemsMethod · 0.80