【Flask + AI】接入CHATGLM API 实现翻译接口

【Flask + AI】接入CHATGLM API 实现翻译接口

最近的项目中,需要加一个翻译功能,正好chatglm4发布了,于是决定着手用它实现。

https://chatglm.cn

准备

首先,在chatglm开发者中心申请api key,这里不再赘述

其次,选择自己的开发框架,这里以 flask 为例

提示词

要实现翻译功能,一个优良的提示词十分重要。

经过多次测试,得到了这样一个较为稳定的提示词。

python 复制代码
prompt_translation = """
    zh-en translation of "input".
    Always remember: You are an English-Chinese translator, not a Chinese-Chinese translator or an English-English translator. 
    Your output should only contains Chinese or English!
    You should Always just do the translate part and do not change its meaning! 
    
    example1:
    input:"write me a poem",
    output:"帮我写一首诗"
    
    example2:
    input:"你好世界",
    output:"hello world"
    
    Now I will give you my input:
"""

这个Prompt 实现了中英互译,注意,这两个例子非常重要,如果没有,模型可能会永远输出英文或者中文。在调用api时,把这个提示词设置为 assistant 可以减小模型把这段话认为是指令的概率。

接口代码

python 复制代码
@glm_blueprint.route('/api/glmTranslation', methods=['POST'])
def translation():
    user_content = request.json.get('user-content')
    if not user_content:
        return jsonify({'error': 'No user-content provided'}), 400

    contentPrompt = prompt_translation

    completion = client.chat.completions.create(
        model='glm-4',
        messages=[
            {"role": "system", "content": contentPrompt},
            {"role": "assistant", "content": user_content}
        ],
        max_tokens=200,
        temperature=0.1,
    )

    # 将 ChatCompletionMessage 对象转换为可序列化的格式
    response_message = completion.choices[0].message.content if completion.choices[0].message else "No response"

    return jsonify({"response": response_message})
  • role 设置为 assistant 或 user 效果会不同
  • 模型可以自己更改,glm-4目前效果最好
  • 如果要节省token,可以限制max_token
相关推荐
得一录1 分钟前
AI 语音助手:如何用大模型优化智能语音交互?
人工智能
玄同7652 分钟前
Python 自动发送邮件实战:用 QQ/163 邮箱发送大模型生成的内容
开发语言·人工智能·python·深度学习·机器学习·邮件·邮箱
逸俊晨晖2 分钟前
NVIDIA 4090的8路1080p实时YOLOv8目标检测
人工智能·yolo·目标检测·nvidia
岱宗夫up3 分钟前
神经网络(MLP)在时间序列预测中的实践应用
python
我的xiaodoujiao3 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 46--撰写 README项目说明文档文件
python·学习·测试工具·pytest
Olamyh4 分钟前
【手搓 ReAct Agent:告别框架,回归本质】
人工智能·python
seaside20034 分钟前
大模型计算量、显存计算方法推导
人工智能·大模型
AI资源库5 分钟前
nvidiapersonaplex-7b-v1模型深入解析
人工智能·语言模型·回归
数研小生7 分钟前
Python自然语言处理:NLTK与Gensim库
开发语言·python·自然语言处理
weixin_509138348 分钟前
智能体认知动力学理论和实践
人工智能·智能体·语义空间·认知动力学