@@ -155,19 +155,25 @@ def replace_marker(match):
155155 parts = match .group (1 ).split (":" )
156156 if len (parts ) == 2 and parts [1 ].isdigit ():
157157 original_index = int (parts [1 ])
158- if original_index not in citation_mapping :
159- citation_mapping [original_index ] = len (citation_mapping ) + 1
160- return f"[{ citation_mapping [original_index ]} ]"
161- return match .group (0 )
158+ # Only map citations that exist in the citations array
159+ if original_index < len (answer ["citations" ]):
160+ if original_index not in citation_mapping :
161+ citation_mapping [original_index ] = len (citation_mapping ) + 1
162+ return f"[{ citation_mapping [original_index ]} ]"
163+ # Return empty string for invalid/out-of-range markers
164+ return ""
162165
163166 for msg in messages :
164167 if msg .role == MessageRole .AGENT and msg .text_messages :
165168 answer ["answer" ] = msg .text_messages [- 1 ].text .value
166169 answer ["answer" ] = re .sub (r'【(\d+:\d+)†source】' , replace_marker , answer ["answer" ])
167170 # Filter and reorder citations based on actual usage
168171 if citation_mapping :
172+ # Create reverse mapping to maintain citation order matching markers
173+ reverse_mapping = {v : k for k , v in citation_mapping .items ()}
169174 filtered_citations = []
170- for original_idx in sorted (citation_mapping .keys ()):
175+ for new_idx in sorted (reverse_mapping .keys ()):
176+ original_idx = reverse_mapping [new_idx ]
171177 if original_idx < len (answer ["citations" ]):
172178 filtered_citations .append (answer ["citations" ][original_idx ])
173179 answer ["citations" ] = filtered_citations
0 commit comments