使用LLM(Ollama部署)为Bertopic确定的主题命名

使用本地部署的 Ollama + Qwen3:14b 模型,结合 BERTopic 输出的关键词与样本摘要,自动生成 3--4 个词的主题名称。整个流程自动化、可复用,适用于学术论文、新闻聚类、客户反馈分析等多种场景。


实现思路

我们设计了一个简单的 Python 函数 generate_topic_name(),它接收两个参数:

  • topic_keywords:由 BERTopic 生成的当前主题关键词列表;
  • sample_abstracts:属于该主题的若干样本摘要(用于提供上下文)。

函数构造一个清晰的提示词(prompt),调用本地 Ollama 模型进行推理,并对输出结果进行后处理,移除模型可能生成的 <think>...</think> 思考标签(常见于 Qwen 系列模型),最终返回干净的主题名称。


代码详解

python 复制代码
import ollama
import re

def remove_thinking_tags(text):
    """
    移除所有 <think>...<think> 标签及其内部内容(支持跨行)
    """
    pattern = r'<think>.*?</think>'
    cleaned = re.sub(pattern, '', text, flags=re.DOTALL)
    return cleaned.strip()

def generate_topic_name(topic_keywords, sample_abstracts):
    prompt = f""" /no_thinking

You are a helpful assistant for naming topics from research paper abstracts.
Given the following keywords generated using BERTopic and sample abstracts, generate a short and meaningful topic name.

The topic name should be very short, maximum of 3 to 4 words --- not a sentence or description.

Keywords: {', '.join(topic_keywords)}

Abstracts:
{chr(10).join(f"- {abs}" for abs in sample_abstracts)}

Give a concise 3--4 word topic name:"""

    response = ollama.chat(
        model='Qwen3:14b',
        messages=[
            {'role': 'user', 'content': prompt}
        ],
        options={
            'temperature': 0.7,
            'num_predict': 3000  # 类似 max_tokens
        }
    )
    raw_content = response['message']['content'].strip()
    # 清理 thinking 标签内容
    cleaned_content = remove_thinking_tags(raw_content)
    return cleaned_content

renamed_topics = {}

for entry in llm_input:
    name = generate_topic_name(entry["topic_keywords"], entry["sample_abstracts"][:5])
    renamed_topics[entry["topic_num"]] = name
    print(f"Topic {entry['topic_num']}: {name}")
相关推荐
Zeeland2 小时前
Rudder:让人类与 AI Agent 像真正的团队一样协作
llm·openai·agent
冬奇Lab15 小时前
RAG 系列(十六):Graph RAG——用知识图谱解决多跳关系问题
人工智能·llm
王_teacher19 小时前
GRU (Gated Recurrent Unit,门控循环单元) 原理详解 并且手写GRU模型
人工智能·gru·llm·nlp
吴佳浩20 小时前
OpenClaw最严厉的父亲- 使用优化建议
人工智能·llm·agent
带刺的坐椅1 天前
Spring AI 2.0 GA 倒计时:先别急,来看看 Java AI 框架的另一条路
java·spring·ai·llm·agent·solon
大模型真好玩1 天前
从RAG到LLM Wiki:一文看懂大模型+知识的演进路线
人工智能·llm·deepseek
Fleshy数模1 天前
玩转 LangChain:从 Prompt 模板到多场景 AI 交互实战
人工智能·langchain·llm
王_teacher1 天前
LSTM 原理详解手动编写LSTM模型代码
人工智能·llm·nlp·lstm
还是转转1 天前
深入认识 Agent —— 智能体开发框架
人工智能·llm·agent
玖日大大1 天前
2026十大LLM研究突破:扩散语言模型挑战自回归、Unicode隐形注入、AI操纵性评估 — 大模型从狂飙走向可控
人工智能·语言模型·回归·llm·论文解读·ai agent·ai安全