Selaa lähdekoodia

修改AI服务组件更新参考资料内容展现形式

feix0518 6 päivää sitten
vanhempi
commit
c701d824d4
1 muutettua tiedostoa jossa 45 lisäystä ja 3 poistoa
  1. 45 3
      xinkeaboard-gemini-langgraph_prompt/backend/src/agent/graph.py

+ 45 - 3
xinkeaboard-gemini-langgraph_prompt/backend/src/agent/graph.py

@@ -305,14 +305,56 @@ def finalize_answer(state: OverallState, config: RunnableConfig):
     logger.info("开始:llm.invoke")
     result = llm.invoke(formatted_prompt)
     logger.info("结束:llm.invoke:{}",result)
+    
     # Replace the short urls with the original urls and add all used urls to the sources_gathered
     unique_sources = []
+    citation_map = {}  # Map of short_url to source info
+    citation_numbers = {}  # Map of short_url to citation number
+    
+    # Build source map and assign citation numbers
+    citation_counter = 1
     for source in state["sources_gathered"]:
         if source["short_url"] in result.content:
-            result.content = result.content.replace(
-                source["short_url"], source["value"]
-            )
             unique_sources.append(source)
+            citation_map[source["short_url"]] = source
+            citation_numbers[source["short_url"]] = citation_counter
+            citation_counter += 1
+    
+    # Collect citations from the content
+    citations_in_text = []
+    
+    # Find all citations in the content and replace them with numbered markers
+    import re
+    
+    # Pattern to match markdown links like [text](url)
+    link_pattern = r'\[([^\]]+)\]\(([^)]+)\)'
+    
+    def replace_with_numbered_citation(match):
+        text = match.group(1)
+        url = match.group(2)
+        if url in citation_numbers:
+            # Store the citation for later use
+            citations_in_text.append((citation_numbers[url], text, citation_map[url]))
+            # Return just the text with a numbered citation marker
+            return f"{text}[{citation_numbers[url]}]"
+        return match.group(0)  # Return unchanged if not a citation
+    
+    # Replace inline citations with numbered markers
+    result.content = re.sub(link_pattern, replace_with_numbered_citation, result.content)
+    
+    # Add a section for citations at the end
+    if citations_in_text:
+        # Sort citations by their number
+        citations_in_text.sort(key=lambda x: x[0])
+        
+        # Add citations section
+        result.content += "\n\n## 参考资料\n"
+        added_citations = set()  # To avoid duplicates
+        for num, text, source in citations_in_text:
+            if num not in added_citations:
+                result.content += f"{num}. [{source['label']}]({source['value']})\n"
+                added_citations.add(num)
+    
     #save the result to a markdown file
     # with open(f"result_{get_research_topic(state['messages'])}.md", "w", encoding="utf-8") as f:
     #     f.write(result.content)