【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
相关推荐
Dilee3 分钟前
Spring AI 接 RAG 最小 Demo:DeepSeek、Ollama、SimpleVectorStore 一次跑通
后端
蝎子莱莱爱打怪1 小时前
AI Agent 相关知识扫盲:16 个概念+11张图+38个开源项目推荐
人工智能·github·agent
甲维斯1 小时前
Fable+Codex 《坦克大战3D》双端发布了!
人工智能·ai编程·游戏开发
掘金一周2 小时前
企业中要做智能体,最佳的方案是什么? | 沸点周刊 6.18
前端·人工智能·ai编程
ClouGence2 小时前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
Gopher_HBo2 小时前
Go语言学习笔记(十二)Tcp实现Rpc
后端
糖拌西瓜皮3 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
雪隐3 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端
洛宇3 小时前
再谈 AI 时代,程序员的失眠问题。
人工智能