### 智谱大模型 GLM-4 https://www.bigmodel.cn/dev/api/normal-model/glm-4
import os
import json
import requests
def text_classification(text, labels):
# 正确解码Unicode标签
decoded_labels = [label for label in labels]
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer *******" # 替换为有效API Key
}
# 构建分类提示词(明确标签格式)
prompt = f"""你是一个专业的长文本分类分析专家,需要完成以下任务:
1. 分析文本内容:"{text}"
2. 从以下标签中选择最合适的类别(仅返回标签名称):
{json.dumps(decoded_labels, ensure_ascii=False)} # 禁用ASCII转义
3. 输出格式要求:纯文本,无额外说明
示例:
输入:"如何提高Python编程效率?"
输出:"教育培训"
"""
payload = {
"model": 'glm-4-flash-250414',
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.1,
"max_tokens": 10000,
"response_format": {"type": "text"}
}
try:
response = requests.post(
url='https://open.bigmodel.cn/api/paas/v4/chat/completions',
headers=headers,
data=json.dumps(payload)
)
response.raise_for_status()
# 打印完整响应用于调试
print("完整响应:", response.text)
# 修正解析逻辑
result = response.json()["choices"][0]["message"]["content"].strip()
return result
except Exception as e:
print(f"API Error: {str(e)}")
return None
# 示例调用(标签已转换为中文)
labels = ["你的label列表"]
#print(f"分类结果:{text_classification(text, labels)}")
new_label = text_classification(text, labels)