使用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}")
相关推荐
冬奇Lab13 小时前
Agent 系列(19):Harness 完整体系——8 层防护框架全景
人工智能·llm·agent
逻极13 小时前
Hermes Agent深度探索:一个会自我沉淀经验的终端智能体
架构·llm·agent·rag·多智能体系统·hermes agent·hermes
stereohomology19 小时前
让AI精确修改视觉可见的细节是繁琐的
llm·多模态编辑
AndrewHZ19 小时前
【LLM技术全景】开源大模型生态:如何选择适合你的基座模型?
人工智能·深度学习·语言模型·开源·llm·transformer·基座模型
troubles maker1 天前
LLaMA-Adapter V2: Parameter-Efficient Visual Instruction Model
llm·nlp·llama·多模态
老梁agent1 天前
一个工程师的 LLM 理论入门:Transformer、Attention 和 Tokenization(不带公式)
物联网·llm
hdsoft_huge1 天前
部署 Nacos + Ollama + vLLM + MCP 完整图文教程(1Panel 面板,命令行安装两种方式)
python·vllm·ollama·mcp
没有腰的嘟嘟嘟1 天前
Easy-agent介绍
ai·llm·agent·rag·skill·spring ai·mcp
Shawn_Shawn1 天前
Apache Doris Ai Function学习
后端·llm
DigitalOcean1 天前
微调后的 LLM 如何部署到生产环境?从GPU 推理端点的搭建、测试与上线全流程
llm·gpu