【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
相关推荐
AAD555888993 小时前
数字仪表LCD显示识别与读数:数字0-9、小数点及单位kwh检测识别实战
python
开源技术5 小时前
Python Pillow 优化,打开和保存速度最快提高14倍
开发语言·python·pillow
Niuguangshuo5 小时前
深入解析Stable Diffusion基石——潜在扩散模型(LDMs)
人工智能·计算机视觉·stable diffusion
迈火5 小时前
SD - Latent - Interposer:解锁Stable Diffusion潜在空间的创意工具
人工智能·gpt·计算机视觉·stable diffusion·aigc·语音识别·midjourney
wfeqhfxz25887825 小时前
YOLO13-C3k2-GhostDynamicConv烟雾检测算法实现与优化
人工智能·算法·计算机视觉
芝士爱知识a6 小时前
2026年AI面试软件推荐
人工智能·面试·职场和发展·大模型·ai教育·考公·智蛙面试
Li emily6 小时前
解决港股实时行情数据 API 接入难题
人工智能·python·fastapi
Aaron15886 小时前
基于RFSOC的数字射频存储技术应用分析
c语言·人工智能·驱动开发·算法·fpga开发·硬件工程·信号处理
J_Xiong01176 小时前
【Agents篇】04:Agent 的推理能力——思维链与自我反思
人工智能·ai agent·推理
wfeqhfxz25887826 小时前
农田杂草检测与识别系统基于YOLO11实现六种杂草自动识别_1
python