目录
[1. 遍历输入句子](#1. 遍历输入句子)
[2. 显示推理状态](#2. 显示推理状态)
[3. 构造提示词](#3. 构造提示词)
[4. 调用模型进行推理](#4. 调用模型进行推理)
[5. 处理模型响应](#5. 处理模型响应)
[6. 输出结果](#6. 输出结果)
摘要:
这段代码实现了一个基于Qwen2.5-7B模型的文本分类系统。主要流程包括:1)初始化分类类别和示例;2)构造提示词并调用本地模型进行推理;3)处理并输出分类结果。系统支持四种预设类别(新闻报道、财务报告、公司公告、分析师报告),通过few-shot learning方式提供示例,并采用rich库实现高亮显示输出。代码结构清晰,包含初始化、推理和主执行三个主要部分,适用于金融领域文本的自动分类任务。
代码结构解析
1. 遍历输入句子
python
for sentence in sentences:
- 对输入的每个句子逐一处理
2. 显示推理状态
python
with console.status("[bold bright_green] Model Inference..."):
-
使用
console.status()
创建一个状态指示器 -
在模型推理时显示"Model Inference..."提示信息
3. 构造提示词
python
sentence_with_prompt = f""{sentence}"是 {custom_settings['class_list']} 里的什么类别?"
-
将当前句子包装成提问形式
-
示例:假设句子是"今天天气真好",class_list是["天气","体育"],则会构造:
"今天天气真好"是 ['天气', '体育'] 里的什么类别?
4. 调用模型进行推理
python
response = ollama.chat(
model="qwen2.5:7b",
messages=[
*custom_settings["pre_history"],
{"role": "user", "content": sentence_with_prompt},
],
)
-
使用
ollama.chat()
调用本地Qwen2.5 7B模型 -
messages
参数包含:-
*custom_settings["pre_history"]
: 展开前置对话历史(包含系统消息和示例) -
新增的用户提问
-
5. 处理模型响应
python
response = response["message"]["content"]
- 从模型返回的复杂响应中提取出实际的回答内容
6. 输出结果
print(f">>> [bold bright_red]sentence: {sentence}")
print(f">>> [bold bright_green]inference answer: {response}")
print("*" * 70)
-
用红色高亮显示原始句子
-
用绿色高亮显示分类结果
-
用星号分隔线分隔不同句子的结果
完整代码
python
from rich import print # 格式化输出
from rich.console import Console
import ollama
'''
_type是什么
'''
# 提供所有类别以及样例
class_examples = {
"新闻报道": "今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。",
"财务报告": "本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。",
"公司公告": "本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力",
"分析师报告": "最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势",
}
# 初始化prompt,构造ollama需要的message信息
def init_promots():
class_list = list(class_examples.keys())
print(f'class_list',class_list)
pre_history = [
{
"role":"system",
"content":f"现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:{class_list}类别中。",
}
]
for _type,exmpale in class_examples.items():
pre_history.append(
{
"role": "user", "content": f""{exmpale}"是 {class_list} 里的什么类别?"
}
)
pre_history.append({"role": "assistant", "content": _type})
return {"class_list": class_list, "pre_history": pre_history}
# 模型推理
def inference(sentences:list,custom_settings:dict):
"""
:param sentences: 待推理的句子
:param custom_settings: 初始设定,包含人为设定的few-shot example
:return:
"""
# 遍历输入句子
for sentence in sentences:
# [bold]表示文本将以加粗形式显示
# [bright_green]设置文本颜色为亮绿色
# 显示推理状态
with console.status("[bold bright_green] Model Inference..."):
# 构造提示词
sentence_with_prompt = (
f""{sentence}"是 {custom_settings['class_list']} 里的什么类别?"
)
# print(f'sentence_with_prompt--》{sentence_with_prompt}')
# 调用模型进行推理
response = ollama.chat(
model="qwen2:0.5b",
messages=[
*custom_settings["pre_history"],
{"role": "user", "content": sentence_with_prompt},
]
)
response = response["message"]["content"]
print(f">>> [bold bright_red]sentence: {sentence}")
print(f">>> [bold bright_green]inference answer: {response}")
print("*" * 70)
if __name__ == '__main__':
console = Console()
custom_settings = init_promots()
# print(f"custom_settings",custom_settings)
sentences = [
"今日,央行发布公告宣布降低利率,以刺激经济增长。这一降息举措将影响贷款利率,并在未来几个季度内对金融市场产生影响。",
"本公司宣布成功收购一家在创新科技领域领先的公司,这一战略性收购将有助于公司拓展技术能力和加速产品研发。",
"公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
"最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会",
]
inference(sentences, custom_settings)