使用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}")
相关推荐
Together_CZ11 小时前
DeepSeek-V4.1-Flash:Pushing the Limits of KV Cache Compression——推动 KV 缓存压缩的极限
缓存·llm·compression·kv cache·deepseek·v4.1-flash·推动 kv 缓存压缩的极限
桃西西呀15 小时前
你拍的一堆硬币,手机怎么一眼数出有几枚?聊聊边缘、轮廓和模板匹配
人工智能·llm·图像识别
slacker-kian17 小时前
[实践]-让 SAP 工程 Skill 脱离 opencode跑在自定义Agent 上
ai·llm·sap·agent·abap·adt·opencode
武子康20 小时前
CLAUDE.md 越写越长,哪些规则该放到子目录?
人工智能·llm·agent
武子康21 小时前
两台机器跑 vLLM,什么时候才值得引入 Ray?
人工智能·llm·agent
桃西西呀21 小时前
Agent说做完了,其实什么都没改:静默失败原因拆解
人工智能·llm·agent
犀利豆2 天前
为什么全世界的 AI 都画不好一只骑自行车的鹈鹕
人工智能·llm·aigc
武子康2 天前
Codex 后台任务结束了,为什么还不能直接接着用?
人工智能·llm·agent
stereohomology2 天前
智谱的工程师是如何笃定认为这个不会被发现?
llm·薅羊毛·反被·羊毛薅
liulilittle2 天前
mock 规范总纲
ai·自动化·llm·mock·测试·tools