使用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}")
相关推荐
Token炼金师2 小时前
服务的骨架:网关、负载均衡、容灾、弹性与多机房 —— 推理系统架构五柱
人工智能·系统架构·llm·负载均衡·容灾·kv cache·prefix cache
程序员cxuan2 小时前
OceanBase 为什么要做 AI 数据库?
数据库·人工智能·大模型·llm·oceanbase
掉鱼的猫3 小时前
代码审查 Agent Harness 实战:AI 自动 Code Review
java·llm·agent
Token炼金师3 小时前
工程基础设施层:MLOps闭环断裂让模型上线即裸奔
人工智能·深度学习·llm
先吃饱再说3 小时前
手写一个 mini-cursor:LangChain Agent 开发完全实战
langchain·llm·agent
chanalbert3 小时前
Agent Skill 工程化指南(三):运行与生效 — 运行时的全链路机制
llm·agent
羞儿4 小时前
llm-algo-8
llm·quantization·flash attention·pagedattention·multi-lora
武子康4 小时前
调查研究-222 PagedAttention 详解:vLLM 如何像操作系统一样管理 KV Cache
人工智能·llm·agent
武子康4 小时前
调查研究-221 KV Cache:LLM 推理服务真正的显存黑洞
人工智能·llm·agent
带刺的坐椅4 小时前
多 Agent 协作实战:任务编排与子代理系统
java·ai·llm·agent·solon·harness